All files / src/app/core/configurations ngrx-state-transfer.ts

47.05% Statements 16/34
50% Branches 6/12
33.33% Functions 4/12
47.05% Lines 16/34

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 7699x   99x 99x 99x     99x   99x   99x             99x                             99x 21x 10x 22x 15x 15x   11x               99x                                                      
import { TransferState, makeStateKey } from '@angular/core';
import { Actions } from '@ngrx/effects';
import { Action, ActionReducer, Store, UPDATE } from '@ngrx/store';
import { pick } from 'lodash-es';
import { first, map, take } from 'rxjs/operators';
 
import { CoreState } from 'ish-core/store/core/core-store';
import { mergeDeep } from 'ish-core/utils/functions';
 
export const NGRX_STATE_SK = makeStateKey<object>('ngrxState');
 
const STATE_ACTION_TYPE = '[Internal] Import NgRx State';
 
let transferredState: object;
 
/**
 * meta reducer for overriding client side state if supplied by server
 */
export function ngrxStateTransferMeta(reducer: ActionReducer<CoreState>): ActionReducer<CoreState> {
  return (state: CoreState, action: Action & { payload: object; features: string[] }) => {
    Iif (action.type === STATE_ACTION_TYPE) {
      transferredState = action.payload;
      return mergeDeep(state, transferredState);
    }
    Iif (action.type === UPDATE && transferredState) {
      // re-apply transferred state as it could be overwritten by uninitialized reducers
      return reducer({ ...state, ...pick(transferredState, ...action.features) }, action);
    }
    return reducer(state, action);
  };
}
 
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- generic store can only be used as any
export function filterState(store: any, maxLevel: number): object {
  if (maxLevel > 0 && store && typeof store === 'object' && !(store instanceof Array)) {
    return Object.keys(store)
      .filter(k => !k.startsWith('_'))
      .map(k => ({ [k]: filterState(store[k], maxLevel - 1) }))
      .reduce((acc, val) => ({ ...acc, ...val }), {});
  } else {
    return store;
  }
}
 
/**
 * Sets state on server-side, re-hydrates on client side.
 * inspired by https://github.com/ngrx/platform/issues/101#issuecomment-351998548
 */
export function ngrxStateTransfer(transferState: TransferState, store: Store, actions: Actions) {
  return () => {
    if (transferState.hasKey(NGRX_STATE_SK)) {
      // browser
      actions.pipe(first()).subscribe(() => {
        const state = transferState.get<object>(NGRX_STATE_SK, undefined);
        transferState.remove(NGRX_STATE_SK);
        store.dispatch({ type: STATE_ACTION_TYPE, payload: state });
      });
    } else {
      // server
      transferState.onSerialize(NGRX_STATE_SK, () => {
        let state;
        store
          .pipe(
            take(1),
            map(s => filterState(s, 2))
          )
          .subscribe((saveState: object) => {
            state = saveState;
          });
 
        return state;
      });
    }
  };
}