Skip to content

Commit d06a164

Browse files
committed
(feat): simple version of transforms
- object with `toStorage` and `fromStorage` functions - `toStorage` is called after removing whitelist and blacklists and before serializing to JSON - `fromStorage` is called after deserializing from JSON
1 parent 10d4cd7 commit d06a164

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

src/index.ts

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,21 @@ export interface IOptions {
99
storage?: any,
1010
jsonify?: boolean,
1111
readonly whitelist?: Array<string>,
12-
readonly blacklist?: Array<string>
12+
readonly blacklist?: Array<string>,
13+
readonly transforms?: Array<ITransform>
1314
}
1415
type StrToAnyMap = {[key: string]: any}
1516

17+
export interface ITransform {
18+
readonly toStorage?: ITransformArgs,
19+
readonly fromStorage?: ITransformArgs
20+
}
21+
export interface ITransformArgs {
22+
(snapshot: StrToAnyMap): StrToAnyMap
23+
}
24+
1625
export const persist: IArgs = (name, store, options = {}) => {
17-
let {storage, jsonify, whitelist, blacklist} = options
26+
let {storage, jsonify, whitelist, blacklist, transforms = []} = options
1827

1928
// use AsyncLocalStorage by default (or if localStorage was passed in)
2029
if (
@@ -45,6 +54,10 @@ export const persist: IArgs = (name, store, options = {}) => {
4554
}
4655
})
4756

57+
transforms.forEach((transform) => {
58+
if (transform.toStorage) { transform.toStorage(snapshot) }
59+
})
60+
4861
const data = !jsonify ? snapshot : JSON.stringify(snapshot)
4962
storage.setItem(name, data)
5063
})
@@ -54,6 +67,12 @@ export const persist: IArgs = (name, store, options = {}) => {
5467
const snapshot = !isString(data) ? data : JSON.parse(data)
5568
// don't apply falsey (which will error), leave store in initial state
5669
if (!snapshot) { return }
70+
71+
// in reverse order, like a stack, so that last transform is first
72+
transforms.slice().reverse().forEach((transform) => {
73+
if (transform.fromStorage) { transform.fromStorage(snapshot) }
74+
})
75+
5776
applySnapshot(store, snapshot)
5877
})
5978
}

0 commit comments

Comments
 (0)