Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.ts

110 lines3.0 KB

1import { noop } from '../core/utils'
2import { PersistedClient, Persister } from '../persistQueryClient'
3​
4interface CreateWebStoragePersisterOptions {
5 /** The storage client used for setting an retrieving items from cache */
6 storage: Storage
7 /** The key to use when storing the cache */
8 key?: string
9 /** To avoid spamming,
10 * pass a time in ms to throttle saving the cache to disk */
11 throttleTime?: number
12 /**
13 * How to serialize the data to storage.
14 * @default `JSON.stringify`
15 */
16 serialize?: (client: PersistedClient) => string
17 /**
18 * How to deserialize the data from storage.
19 * @default `JSON.parse`
20 */
21 deserialize?: (cachedString: string) => PersistedClient
23​
24export function createWebStoragePersister({
25 storage,
26 key = `REACT_QUERY_OFFLINE_CACHE`,
27 throttleTime = 1000,
28 serialize = JSON.stringify,
29 deserialize = JSON.parse,
30}: CreateWebStoragePersisterOptions): Persister {
31 //try to save data to storage
32 function trySave(persistedClient: PersistedClient) {
33 try {
34 storage.setItem(key, serialize(persistedClient))
35 } catch {
36 return false
37 }
38 return true
39 }
40​
41 if (typeof storage !== 'undefined') {
42 return {
43 persistClient: throttle(persistedClient => {
44 if (trySave(persistedClient) !== true) {
45 const mutations = [...persistedClient.clientState.mutations]
46 const queries = [...persistedClient.clientState.queries]
47 const client: PersistedClient = {
48 ...persistedClient,
49 clientState: { mutations, queries },
50 }
51​
52 // sort queries by dataUpdatedAt (oldest first)
53 const sortedQueries = [...queries].sort(
54 (a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt
55 )
56 // clean old queries and try to save
57 while (sortedQueries.length > 0) {
58 const oldestData = sortedQueries.shift()
59 client.clientState.queries = queries.filter(q => q !== oldestData)
60 if (trySave(client)) {
61 return // save success
62 }
63 }
64​
65 // clean mutations and try to save
66 while (mutations.shift()) {
67 if (trySave(client)) {
68 return // save success
69 }
70 }
71 }
72 }, throttleTime),
73 restoreClient: () => {
74 const cacheString = storage.getItem(key)
75​
76 if (!cacheString) {
77 return
78 }
79​
80 return deserialize(cacheString) as PersistedClient
81 },
82 removeClient: () => {
83 storage.removeItem(key)
84 },
85 }
86 }
87​
88 return {
89 persistClient: noop,
90 restoreClient: noop,
91 removeClient: noop,
92 }
94​
95function throttle<TArgs extends any[]>(
96 func: (...args: TArgs) => any,
97 wait = 100
98) {
99 let timer: ReturnType<typeof setTimeout> | null = null
100 let params: TArgs
101 return function (...args: TArgs) {
102 params = args
103 if (timer === null) {
104 timer = setTimeout(() => {
105 func(...params)
106 timer = null
107 }, wait)
108 }
109 }