All files / src/app/core/utils ngrx-creators.ts

100% Statements 26/26
88.88% Branches 8/9
100% Functions 13/13
100% Lines 20/20

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 55484x       484x 40078x     484x 22003x         484x 1058x       1058x     484x 441x       441x       367x 2x   367x     484x 783x         783x     484x 691x         691x    
import { on } from '@ngrx/store';
 
import { HttpError } from 'ish-core/models/http-error/http-error.model';
 
export function payload<P>() {
  return (args: P) => ({ payload: { ...args } });
}
 
export function httpError<P = {}>() {
  return (args: { error: HttpError } & P) => ({ payload: { ...args } });
}
 
/* eslint-disable @typescript-eslint/no-explicit-any */
 
export function setLoadingOn<S = any>(...actionCreators: any) {
  const stateFnc = (state: any) => ({
    ...state,
    loading: typeof state.loading === 'boolean' ? true : state.loading + 1,
  });
  return on<S, any>(...actionCreators, stateFnc);
}
 
export function unsetLoadingOn<S = any>(...actionCreators: any) {
  const stateFnc = (state: any) => ({
    ...state,
    loading: typeof state.loading === 'boolean' ? false : state.loading - 1,
  });
  return on<S, any>(...actionCreators, stateFnc);
}
 
function calculateLoading<T extends boolean | number, S extends { loading: T }>(state: S): T {
  if (typeof state.loading === 'number' && state.loading - 1 < 0) {
    console.warn('State loading would be decreased below 0.');
  }
  return (typeof state.loading === 'boolean' ? false : Math.max((state.loading as number) - 1, 0)) as T;
}
 
export function unsetLoadingAndErrorOn<S = any>(...actionCreators: any) {
  const stateFnc = (state: any) => ({
    ...state,
    loading: calculateLoading(state),
    error: undefined as HttpError,
  });
  return on<S, any>(...actionCreators, stateFnc);
}
 
export function setErrorOn<S = any>(...actionCreators: any) {
  const stateFnc = (state: any, action: { payload: { error: HttpError }; type: string }) => ({
    ...state,
    error: action.payload.error,
    loading: calculateLoading(state),
  });
  return on<S, any>(...actionCreators, stateFnc);
}