Skip to content

Commit

Permalink
feat: add optional functions to serialize and deserialize from Storag…
Browse files Browse the repository at this point in the history
…e Persistors
  • Loading branch information
bengry committed Oct 31, 2021
1 parent 69a5d79 commit 2b2c22f
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
14 changes: 12 additions & 2 deletions src/createAsyncStoragePersistor-experimental/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,26 @@ interface CreateAsyncStoragePersistorOptions {
/** To avoid spamming,
* pass a time in ms to throttle saving the cache to disk */
throttleTime?: number
/**
* @defualt `JSON.stringify`
*/
serialize?: (client: PersistedClient) => string;
/**
* @defualt `JSON.parse`
*/
deserialize?: (cachedString: string) => PersistedClient;
}

export const createAsyncStoragePersistor = ({
storage,
key = `REACT_QUERY_OFFLINE_CACHE`,
throttleTime = 1000,
serialize = JSON.stringify,
deserialize = JSON.parse,
}: CreateAsyncStoragePersistorOptions): Persistor => {
return {
persistClient: asyncThrottle(
persistedClient => storage.setItem(key, JSON.stringify(persistedClient)),
persistedClient => storage.setItem(key, serialize(persistedClient)),
{ interval: throttleTime }
),
restoreClient: async () => {
Expand All @@ -33,7 +43,7 @@ export const createAsyncStoragePersistor = ({
return
}

return JSON.parse(cacheString) as PersistedClient
return deserialize(cacheString) as PersistedClient
},
removeClient: () => storage.removeItem(key),
}
Expand Down
16 changes: 14 additions & 2 deletions src/createWebStoragePersistor-experimental/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,29 @@ interface CreateWebStoragePersistorOptions {
/** To avoid spamming,
* pass a time in ms to throttle saving the cache to disk */
throttleTime?: number
/**
* How to serialize the data to storage.
* @defualt `JSON.stringify`
*/
serialize?: (client: PersistedClient) => string;
/**
* How to deserialize the data from storage.
* @defualt `JSON.parse`
*/
deserialize?: (cachedString: string) => PersistedClient;
}

export function createWebStoragePersistor({
storage,
key = `REACT_QUERY_OFFLINE_CACHE`,
throttleTime = 1000,
serialize = JSON.stringify,
deserialize = JSON.parse,
}: CreateWebStoragePersistorOptions): Persistor {
if (typeof storage !== 'undefined') {
return {
persistClient: throttle(persistedClient => {
storage.setItem(key, JSON.stringify(persistedClient))
storage.setItem(key, serialize(persistedClient))
}, throttleTime),
restoreClient: () => {
const cacheString = storage.getItem(key)
Expand All @@ -28,7 +40,7 @@ export function createWebStoragePersistor({
return
}

return JSON.parse(cacheString) as PersistedClient
return deserialize(cacheString) as PersistedClient
},
removeClient: () => {
storage.removeItem(key)
Expand Down

0 comments on commit 2b2c22f

Please sign in to comment.