All files / src/app/core/store/shopping/search search.reducer.ts

92.3% Statements 12/13
57.14% Branches 4/7
66.66% Functions 2/3
92.3% Lines 12/13

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 5617x       17x   17x                             17x             17x   17x               2x           7x     7x 7x 7x     7x      
import { createReducer, on } from '@ngrx/store';
 
import { HttpError } from 'ish-core/models/http-error/http-error.model';
import { Suggestions } from 'ish-core/models/suggestions/suggestions.model';
import { setErrorOn, setLoadingOn, unsetLoadingAndErrorOn } from 'ish-core/utils/ngrx-creators';
 
import {
  addSearchTermToSuggestion,
  removeSuggestions,
  suggestSearch,
  suggestSearchFail,
  suggestSearchSuccess,
} from './search.actions';
 
export interface SearchState {
  suggestions: Suggestions;
  _searchTerms: string[];
  loading: boolean;
  error: HttpError;
}
 
const initialState: SearchState = {
  suggestions: undefined,
  _searchTerms: SSR ? [] : localStorage.getItem('_searchTerms') ? JSON.parse(localStorage.getItem('_searchTerms')) : [],
  loading: false,
  error: undefined,
};
 
const MAX_NUMBER_OF_STORED_SEARCH_TERMS = 5;
 
export const searchReducer = createReducer(
  initialState,
  setLoadingOn(suggestSearch),
  unsetLoadingAndErrorOn(suggestSearchSuccess),
  setErrorOn(suggestSearchFail),
  on(removeSuggestions, (state): SearchState => ({ ...state, suggestions: undefined })),
  on(
    suggestSearchSuccess,
    (state, action): SearchState => ({
      ...state,
      suggestions: action.payload.suggestions,
    })
  ),
  on(addSearchTermToSuggestion, (state, action): SearchState => {
    const newSearchTerms = state._searchTerms.includes(action.payload.searchTerm)
      ? [...state._searchTerms]
      : [action.payload.searchTerm, ...state._searchTerms].slice(0, MAX_NUMBER_OF_STORED_SEARCH_TERMS);
    const newState = { ...state, _searchTerms: newSearchTerms };
    if (!SSR) {
      localStorage.setItem('_searchTerms', JSON.stringify(newState._searchTerms));
    }
 
    return newState;
  })
);