Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: storage syncing for feature stores #249

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 33 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

![bundle size](https://img.shields.io/bundlephobia/minzip/ngrx-store-localstorage)
![npm weekly downloads](https://img.shields.io/npm/dw/ngrx-store-localstorage)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![CircleCI](https://circleci.com/gh/btroncone/ngrx-store-localstorage.svg?style=svg)](https://circleci.com/gh/btroncone/ngrx-store-localstorage)

Simple syncing between ngrx store and local or session storage.
Expand Down Expand Up @@ -47,6 +47,33 @@ const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];
export class MyAppModule {}
```

3. For feature modules, enable the `forFeature` flag

```ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule, ActionReducerMap, ActionReducer, MetaReducer } from '@ngrx/store';
import { localStorageSync } from 'ngrx-store-localstorage';
import { featureReducer } from './reducer';

export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
return localStorageSync({keys: ['todos'], forFeature: true})(reducer);
}
const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];

@NgModule({
imports: [
BrowserModule,
StoreModule.forFeature(
'feature',
featureReducer,
{metaReducers}
)
]
})
export class MyFeatureModule {}
```

## API

### `localStorageSync(config: LocalStorageConfig): Reducer`
Expand Down Expand Up @@ -97,25 +124,26 @@ An interface defining the configuration attributes to bootstrap `localStorageSyn
* `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`.
* `forFeature` \(*boolean? = false*): Specify if the storage sync should be performed for a feature store.

### Usage

#### Key Prefix

```ts
localStorageSync({
keys: ['todos', 'visibilityFilter'],
storageKeySerializer: (key) => `cool_${key}`,
keys: ['todos', 'visibilityFilter'],
storageKeySerializer: (key) => `cool_${key}`,
});
```
```
In above 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`.

#### Target Depth Configuration

```ts
localStorageSync({
keys: [
{ feature1: [{ slice11: ['slice11_1'], slice14: ['slice14_2'] }] },
{ feature1: [{ slice11: ['slice11_1'], slice14: ['slice14_2'] }] },
{ feature2: ['slice21'] }
],
});
Expand Down
30 changes: 19 additions & 11 deletions projects/lib/src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ export const rehydrateApplicationState = (
keys: Keys,
storage: Storage,
storageKeySerializer: (key: string) => string,
restoreDates: boolean
restoreDates: boolean,
forFeature: boolean
) => {
return (keys as any[]).reduce((acc, curr) => {
let key = curr;
Expand Down Expand Up @@ -93,8 +94,10 @@ export const rehydrateApplicationState = (
raw = JSON.parse(stateSlice, reviver);
}

return Object.assign({}, acc, {
[key]: deserialize ? deserialize(raw) : raw,
const rehydratedState = deserialize ? deserialize(raw) : raw;

return forFeature ? rehydratedState : Object.assign({}, acc, {
[key]: rehydratedState,
});
}
}
Expand Down Expand Up @@ -132,7 +135,8 @@ export const syncStateUpdate = (
storage: Storage,
storageKeySerializer: (key: string | number) => string,
removeOnUndefined: boolean,
syncCondition?: (state: any) => any
syncCondition?: (state: any) => any,
forFeature?: boolean
) => {
if (syncCondition) {
try {
Expand All @@ -149,14 +153,14 @@ export const syncStateUpdate = (
}

keys.forEach((key: string | KeyConfiguration | Options | ((key: string, value: any) => any)): void => {
let stateSlice = state[key as string];
let stateSlice = state?.[key as string];
let replacer;
let space: string | number;
let encrypt;

if (typeof key === 'object') {
let name = Object.keys(key)[0];
stateSlice = state[name];
stateSlice = forFeature ? state : state[name];

if (typeof stateSlice !== 'undefined' && key[name]) {
// use serialize function if specified.
Expand Down Expand Up @@ -188,14 +192,16 @@ export const syncStateUpdate = (
}

/*
Replacer and space arguments to pass to JSON.stringify.
If these fields don't exist, undefined will be passed.
*/
Replacer and space arguments to pass to JSON.stringify.
If these fields don't exist, undefined will be passed.
*/
replacer = key[name].replacer;
space = key[name].space;
}

key = name;
} else if (typeof key === 'string') {
stateSlice = forFeature ? state : state[key];
}

if (typeof stateSlice !== 'undefined' && storage !== undefined) {
Expand Down Expand Up @@ -262,7 +268,7 @@ export const localStorageSync = (config: LocalStorageConfig) => (reducer: any) =

const stateKeys = validateStateKeys(config.keys);
const rehydratedState = config.rehydrate
? rehydrateApplicationState(stateKeys, config.storage, config.storageKeySerializer, config.restoreDates)
? rehydrateApplicationState(stateKeys, config.storage, config.storageKeySerializer, config.restoreDates, config.forFeature)
: undefined;

return function (state: any, action: any) {
Expand All @@ -289,7 +295,8 @@ export const localStorageSync = (config: LocalStorageConfig) => (reducer: any) =
config.storage,
config.storageKeySerializer as (key: string | number) => string,
config.removeOnUndefined,
config.syncCondition
config.syncCondition,
config.forFeature
);
}

Expand All @@ -307,6 +314,7 @@ export interface LocalStorageConfig {
syncCondition?: (state: any) => any;
checkStorageAvailability?: boolean;
mergeReducer?: (state: any, rehydratedState: any, action: any) => any;
forFeature?: boolean;
}

interface KeyConfiguration {
Expand Down
Loading