All files / src/store/modules splits.module.js

100% Statements 76/76
90.54% Branches 67/74
100% Functions 18/18
100% Lines 76/76

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209            2x         1x                     2x     2x     2x     2x     2x     1x         5x   5x 1x 1x     5x 1x     5x 1x           5x 1x               12x   12x 12x   12x   12x 1x 1x     11x 1x 1x 1x     10x 10x 10x 10x   10x   10x 20x 20x       10x   10x   8x   8x   8x 7x   8x 7x         8x     2x       2x 2x   2x                   10x               7x 7x   7x 7x   7x 18x 15x       7x   7x   5x   5x   5x 5x       5x   2x       2x 2x   2x                   7x         3x     2x     2x     2x 2x 3x      
import { createErrorObject, getErrorMessage } from '../../utils/errorUtils';
import createLogger from '../../utils/logger';
import {
  NOTIF_FQ, SPLITS_ACT, SPLITS_GET, SPLITS_MUT,
} from '../types';
 
const log = createLogger('splits');
 
export default {
  namespaced: true,
  state() {
    return {
      splitResults: [],
      availableRecipes: [],
      availableSplitOptions: [],
      loading: false,
      error: null,
      lastFetchedAt: null,
    };
  },
  mutations: {
    [SPLITS_MUT.setSplitResults](state, payload) {
      state.splitResults = payload || [];
    },
    [SPLITS_MUT.setAvailableRecipes](state, payload) {
      state.availableRecipes = payload || [];
    },
    [SPLITS_MUT.setAvailableSplitOptions](state, payload) {
      state.availableSplitOptions = payload || [];
    },
    [SPLITS_MUT.setLoading](state, val) {
      state.loading = !!val;
    },
    [SPLITS_MUT.setError](state, errorObject) {
      state.error = errorObject || null;
    },
    [SPLITS_MUT.setLastFetchedAt](state, timestamp) {
      state.lastFetchedAt = timestamp;
    },
  },
  actions: {
    [SPLITS_ACT.hydrate]({ commit }, initial = {}) {
      const pageData = initial.pageData || {};
 
      if (Array.isArray(pageData.splitResults)) {
        commit(SPLITS_MUT.setSplitResults, pageData.splitResults);
        commit(SPLITS_MUT.setLastFetchedAt, Date.now());
      }
 
      if (Array.isArray(pageData.availableRecipes)) {
        commit(SPLITS_MUT.setAvailableRecipes, pageData.availableRecipes);
      }
 
      if (Array.isArray(pageData.availableSplitOptions)) {
        commit(
          SPLITS_MUT.setAvailableSplitOptions,
          pageData.availableSplitOptions,
        );
      }
 
      if (pageData.error) {
        commit(SPLITS_MUT.setError, pageData.error.message);
      }
    },
 
    async [SPLITS_ACT.load](
      { commit, dispatch, state },
      { api, filters = {}, force = false },
    ) {
      const hasExistingData = state.splitResults && state.splitResults.length > 0;
 
      const STALE_TIME = 5 * 60 * 1000;
      const isStale = !state.lastFetchedAt || Date.now() - state.lastFetchedAt > STALE_TIME;
 
      const hasFilters = Object.keys(filters).length > 0;
 
      if (!force && hasExistingData && !isStale && !hasFilters) {
        log.info('Using cached data');
        return;
      }
 
      if (!state.lastFetchedAt && hasExistingData && !hasFilters) {
        log.info('Using SSR hydrated data');
        commit(SPLITS_MUT.setLastFetchedAt, Date.now());
        return;
      }
 
      try {
        Eif (hasFilters) {
          commit(SPLITS_MUT.setLoading, true);
          commit(SPLITS_MUT.setError, null);
 
          const params = new URLSearchParams();
 
          Object.entries(filters).forEach(([key, value]) => {
            Eif (value !== undefined && value !== null && value !== '') {
              params.append(key, value);
            }
          });
 
          log.info('Fetching with params:', params.toString());
 
          const { data } = await api.get(`/api/splits?${params.toString()}`);
 
          log.info('Received data:', data);
 
          const payload = data.data || data;
 
          if (payload.splitResults) {
            commit(SPLITS_MUT.setSplitResults, payload.splitResults);
          }
          if (payload.availableSplitOptions) {
            commit(
              SPLITS_MUT.setAvailableSplitOptions,
              payload.availableSplitOptions,
            );
          }
          commit(SPLITS_MUT.setLastFetchedAt, Date.now());
        }
      } catch (e) {
        const errorObject = createErrorObject(
          e,
          'Failed to load split results',
        );
        log.error('Load error:', errorObject);
        commit(SPLITS_MUT.setError, errorObject);
 
        dispatch(
          NOTIF_FQ.actions.showError,
          {
            message: errorObject.message,
            type: 'api_error',
            closable: true,
          },
          { root: true },
        );
      } finally {
        commit(SPLITS_MUT.setLoading, false);
      }
    },
 
    async [SPLITS_ACT.fetchSplitResults](
      { commit, dispatch },
      { api, filters },
    ) {
      commit(SPLITS_MUT.setLoading, true);
      commit(SPLITS_MUT.setError, null);
 
      try {
        const params = new URLSearchParams();
 
        Object.entries(filters).forEach(([key, value]) => {
          if (value !== undefined && value !== null && value !== '') {
            params.append(key, value);
          }
        });
 
        log.info('fetchSplitResults with params:', params.toString());
 
        const { data } = await api.get(`/api/splits?${params.toString()}`);
 
        log.info('fetchSplitResults received data:', data);
 
        const payload = data.data || data;
 
        commit(SPLITS_MUT.setSplitResults, payload.splitResults || []);
        commit(
          SPLITS_MUT.setAvailableSplitOptions,
          payload.availableSplitOptions || [],
        );
        commit(SPLITS_MUT.setLastFetchedAt, Date.now());
      } catch (error) {
        const errorObject = createErrorObject(
          error,
          'Failed to load split results',
        );
        log.error('fetchSplitResults error:', errorObject);
        commit(SPLITS_MUT.setError, errorObject);
 
        dispatch(
          NOTIF_FQ.actions.showError,
          {
            message: errorObject.message,
            type: 'api_error',
            closable: true,
          },
          { root: true },
        );
      } finally {
        commit(SPLITS_MUT.setLoading, false);
      }
    },
  },
  getters: {
    [SPLITS_GET.splitResults]: (s, _g, root) => (s.splitResults?.length
      ? s.splitResults
      : root.pageData?.splitResults || []),
    [SPLITS_GET.availableRecipes]: (s, _g, root) => (s.availableRecipes?.length
      ? s.availableRecipes
      : root.pageData?.availableRecipes || []),
    [SPLITS_GET.availableSplitOptions]: (s, _g, root) => (s.availableSplitOptions?.length
      ? s.availableSplitOptions
      : root.pageData?.availableSplitOptions || []),
    [SPLITS_GET.isLoading]: (s) => !!s.loading,
    [SPLITS_GET.error]: (s) => s.error || null,
    [SPLITS_GET.errorMessage]: (s) => getErrorMessage(s.error),
  },
};