Skip to content

Commit dc69b30

Browse files
committed
feat(persistor): add an optional persistence mapper function to allow cache filtration
1 parent 7bcb322 commit dc69b30

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

src/Persistor.ts

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import Log from './Log';
22
import Storage from './Storage';
33
import Cache from './Cache';
44

5-
import { ApolloPersistOptions } from './types';
5+
import { ApolloPersistOptions, PersistenceMapperFunction } from './types';
66

77
export interface PersistorConfig<T> {
88
log: Log<T>;
@@ -16,26 +16,38 @@ export default class Persistor<T> {
1616
storage: Storage<T>;
1717
maxSize?: number;
1818
paused: boolean;
19+
persistenceMapper?: PersistenceMapperFunction;
1920

2021
constructor(
2122
{ log, cache, storage }: PersistorConfig<T>,
2223
options: ApolloPersistOptions<T>,
2324
) {
24-
const { maxSize = 1024 * 1024 } = options;
25+
const {
26+
maxSize = 1024 * 1024,
27+
persistenceMapper,
28+
} = options;
2529

2630
this.log = log;
2731
this.cache = cache;
2832
this.storage = storage;
2933
this.paused = false;
3034

35+
if (persistenceMapper) {
36+
this.persistenceMapper = persistenceMapper;
37+
}
38+
3139
if (maxSize) {
3240
this.maxSize = maxSize;
3341
}
3442
}
3543

3644
async persist(): Promise<void> {
3745
try {
38-
const data = this.cache.extract();
46+
let data = this.cache.extract();
47+
48+
if (!this.paused && this.persistenceMapper) {
49+
data = await this.persistenceMapper(data);
50+
}
3951

4052
if (
4153
this.maxSize != null &&

src/types/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ export type TriggerUninstallFunction = () => void;
88

99
export type TriggerFunction = (persist: () => void) => TriggerUninstallFunction;
1010

11+
export type PersistenceMapperFunction = (data: any) => Promise<any>;
12+
1113
export type PersistedData<T> = T | string | null;
1214

1315
export interface PersistentStorage<T> {
@@ -24,5 +26,6 @@ export interface ApolloPersistOptions<TSerialized> {
2426
key?: string;
2527
serialize?: boolean;
2628
maxSize?: number | false;
29+
persistenceMapper?: PersistenceMapperFunction;
2730
debug?: boolean;
2831
}

0 commit comments

Comments
 (0)