|
| 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 | +} |
0 commit comments