Skip to content

Commit cf0cfa1

Browse files
committed
feat(storage-options): use state classes as key
1 parent e7a8ef4 commit cf0cfa1

File tree

3 files changed

+51
-10
lines changed

3 files changed

+51
-10
lines changed

src/lib/async-storage.module.ts

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,7 @@ import {
1212
NGXS_STORAGE_PLUGIN_OPTIONS,
1313
STORAGE_ENGINE
1414
} from './symbols';
15-
16-
export function storageOptionsFactory(options: NgxsStoragePluginOptions) {
17-
return {
18-
key: '@@STATE',
19-
serialize: JSON.stringify,
20-
deserialize: JSON.parse,
21-
...options
22-
};
23-
}
15+
import { storageOptionsFactory } from './internals';
2416

2517
export const USER_OPTIONS = new InjectionToken('USER_OPTIONS');
2618

src/lib/internals.ts

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { StateClass } from '@ngxs/store/internals';
2+
import { NgxsStoragePluginOptions } from './symbols';
3+
/**
4+
* If the `key` option is not provided then the below constant
5+
* will be used as a default key
6+
*/
7+
export const DEFAULT_STATE_KEY = '@@STATE';
8+
9+
/**
10+
* Internal type definition for the `key` option provided
11+
* in the `forRoot` method when importing module
12+
*/
13+
export type StorageKey = string | StateClass | (string | StateClass)[];
14+
15+
/**
16+
* This key is used to retrieve static metadatas on state classes.
17+
* This constant is taken from the core codebase
18+
*/
19+
const META_OPTIONS_KEY = 'NGXS_OPTIONS_META';
20+
21+
function transformKeyOption(key: StorageKey): string[] {
22+
if (!Array.isArray(key)) {
23+
key = [key];
24+
}
25+
26+
return key.map((token: string | StateClass) => {
27+
if (typeof token === 'string') {
28+
return token;
29+
}
30+
31+
const options = (token as any)[META_OPTIONS_KEY];
32+
return options.name;
33+
});
34+
}
35+
36+
export function storageOptionsFactory(
37+
options: NgxsStoragePluginOptions | undefined
38+
): NgxsStoragePluginOptions {
39+
if (options !== undefined && options.key) {
40+
options.key = transformKeyOption(options.key);
41+
}
42+
return {
43+
key: [DEFAULT_STATE_KEY],
44+
serialize: JSON.stringify,
45+
deserialize: JSON.parse,
46+
...options
47+
};
48+
}

src/lib/symbols.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import { InjectionToken } from '@angular/core';
22
import { Observable, of } from 'rxjs';
3+
import { StorageKey } from './internals';
34

45
export interface NgxsStoragePluginOptions {
56
/**
67
* Key for the state slice to store in the storage engine.
78
*/
8-
key?: string | string[] | undefined;
9+
key?: undefined | StorageKey;
910

1011
/**
1112
* Migration strategies.

0 commit comments

Comments
 (0)