Skip to content

Commit

Permalink
feat(persistor): add an optional persistence mapper function to allow…
Browse files Browse the repository at this point in the history
… cache filtration
  • Loading branch information
jspizziri committed Jul 6, 2021
1 parent 7bcb322 commit dc69b30
Showing 2 changed files with 18 additions and 3 deletions.
18 changes: 15 additions & 3 deletions src/Persistor.ts
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@ import Log from './Log';
import Storage from './Storage';
import Cache from './Cache';

import { ApolloPersistOptions } from './types';
import { ApolloPersistOptions, PersistenceMapperFunction } from './types';

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

constructor(
{ log, cache, storage }: PersistorConfig<T>,
options: ApolloPersistOptions<T>,
) {
const { maxSize = 1024 * 1024 } = options;
const {
maxSize = 1024 * 1024,
persistenceMapper,
} = options;

this.log = log;
this.cache = cache;
this.storage = storage;
this.paused = false;

if (persistenceMapper) {
this.persistenceMapper = persistenceMapper;
}

if (maxSize) {
this.maxSize = maxSize;
}
}

async persist(): Promise<void> {
try {
const data = this.cache.extract();
let data = this.cache.extract();

if (!this.paused && this.persistenceMapper) {
data = await this.persistenceMapper(data);
}

if (
this.maxSize != null &&
3 changes: 3 additions & 0 deletions src/types/index.ts
Original file line number Diff line number Diff line change
@@ -8,6 +8,8 @@ export type TriggerUninstallFunction = () => void;

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

export type PersistenceMapperFunction = (data: any) => Promise<any>;

export type PersistedData<T> = T | string | null;

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

0 comments on commit dc69b30

Please sign in to comment.