Skip to content

Commit

Permalink
Merge pull request #135 from rowandh/merge-reducer
Browse files Browse the repository at this point in the history
Add merge reducer option
  • Loading branch information
BBlackwo authored Mar 11, 2020
2 parents cf0b21a + 387051f commit bfb31dd
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 8 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ An interface defining the configuration attributes to bootstrap `localStorageSyn
* `restoreDates` \(*boolean? = true*): Restore serialized date objects. If you work directly with ISO date strings, set this option to `false`.
* `syncCondition` (optional) `(state) => boolean`: When set, sync to storage medium will only occur when this function returns a true boolean. Example: `(state) => state.config.syncToStorage` will check the state tree under config.syncToStorage and if true, it will sync to the storage. If undefined or false it will not sync to storage. Often useful for "remember me" options in login.
* `checkStorageAvailability` \(*boolean? = false*): Specify if the storage availability checking is expected, i.e. for server side rendering / Universal.
* `mergeReducer` (optional) `(state: any, rehydratedState: any, action: any) => any`: Defines the reducer to use to merge the rehydrated state from storage with the state from the ngrx store. If unspecified, defaults to performing a full deepmerge on an `INIT_ACTION` or an `UPDATE_ACTION`.

Usage: `localStorageSync({keys: ['todos', 'visibilityFilter'], storageKeySerializer: (key) => 'cool_' + key, ... })`. In this example `Storage` will use keys `cool_todos` and `cool_visibilityFilter` keys to store `todos` and `visibilityFilter` slices of state). The key itself is used by default - `(key) => key`.

Expand Down
42 changes: 42 additions & 0 deletions spec/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { syncStateUpdate, rehydrateApplicationState, dateReviver, localStorageSy
import * as CryptoJS from 'crypto-js';
import 'localstorage-polyfill';
const INIT_ACTION = '@ngrx/store/init';
import * as deepmerge from 'deepmerge';

// Very simple classes to test serialization options. They cover string, number, date, and nested classes
// The top level class has static functions to help test reviver, replacer, serialize and deserialize
Expand Down Expand Up @@ -486,4 +487,45 @@ describe('ngrxLocalStorage', () => {
feature2: { slice21: true, slice22: [1, 2], slice23: {} },
});
});

it('should enable a complex merge of rehydrated storage and state', () => {
const initialState = {
app: { app1: false, app2: [], app3: {} },
feature1: { slice11: false, slice12: [], slice13: {} },
feature2: { slice21: false, slice22: [], slice23: {} },
};

// A legit case where state is saved in chunks rather than as a single object
localStorage.setItem('feature1', JSON.stringify({ slice11: true, slice12: [1, 2] }));
localStorage.setItem('feature2', JSON.stringify({ slice21: true, slice22: [1, 2] }));

// Set up reducers
const reducer = (state = initialState, action) => state;
const mergeReducer = (state, rehydratedState, action) => {
// Perform a merge where we only want a single property from feature1
// but a deepmerge with feature2

return {
...state,
feature1: {
slice11: rehydratedState.feature1.slice11
},
feature2: deepmerge(state.feature2, rehydratedState.feature2)
}
}
const metaReducer = localStorageSync({keys: [
{'feature1': ['slice11', 'slice12']},
{'feature2': ['slice21', 'slice22']},
], rehydrate: true, mergeReducer});

const action = {type: INIT_ACTION};

// Resultant state should merge the rehydrated partial state and our initial state
const finalState = metaReducer(reducer)(initialState, action);
expect(finalState).toEqual({
app: { app1: false, app2: [], app3: {} },
feature1: { slice11: true },
feature2: { slice21: true, slice22: [1, 2], slice23: {} },
});
});
});
35 changes: 27 additions & 8 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,21 @@ export const syncStateUpdate = (
});
};

// Default merge strategy is a full deep merge.
export const defaultMergeReducer = (state: any, rehydratedState: any, action: any) => {

if ((action.type === INIT_ACTION || action.type === UPDATE_ACTION) && rehydratedState) {
const overwriteMerge = (destinationArray, sourceArray, options) => sourceArray;
const options: deepmerge.Options = {
arrayMerge: overwriteMerge
};

state = deepmerge(state, rehydratedState, options);
}

return state;
};

export const localStorageSync = (config: LocalStorageConfig) => (
reducer: any
) => {
Expand All @@ -236,6 +251,13 @@ export const localStorageSync = (config: LocalStorageConfig) => (
config.restoreDates = true;
}

// Use default merge reducer.
let mergeReducer = config.mergeReducer;

if (mergeReducer === undefined || typeof(mergeReducer) !== 'function') {
mergeReducer = defaultMergeReducer;
}

const stateKeys = validateStateKeys(config.keys);
const rehydratedState = config.rehydrate
? rehydrateApplicationState(
Expand All @@ -257,14 +279,10 @@ export const localStorageSync = (config: LocalStorageConfig) => (
nextState = { ...state };
}

if ((action.type === INIT_ACTION || action.type === UPDATE_ACTION) && rehydratedState) {
const overwriteMerge = (destinationArray, sourceArray, options) => sourceArray;
const options: deepmerge.Options = {
arrayMerge: overwriteMerge
};
nextState = deepmerge(nextState, rehydratedState, options);
}

// Merge the store state with the rehydrated state using
// either a user-defined reducer or the default.
nextState = mergeReducer(nextState, rehydratedState, action);

nextState = reducer(nextState, action);

if (action.type !== INIT_ACTION) {
Expand Down Expand Up @@ -313,4 +331,5 @@ export interface LocalStorageConfig {
storageKeySerializer?: (key: string) => string;
syncCondition?: (state: any) => any;
checkStorageAvailability?: boolean;
mergeReducer?: (state: any, rehydratedState: any, action: any) => any;
}

0 comments on commit bfb31dd

Please sign in to comment.