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

retryStrategies.ts

42 lines1.3 KB

1import type { PersistedClient } from './persist'
2​
3/**
4 * Called when saving the persisted client fails. Returns a smaller client to
5 * try saving again, or `undefined` to give up.
6 */
7export type PersistRetryer = (props: {
8 persistedClient: PersistedClient
9 error: Error
10 errorCount: number
11}) => PersistedClient | undefined
12​
13/**
14 * A {@link PersistRetryer} that drops the query with the oldest `dataUpdatedAt`
15 * and tries again, until no queries are left.
16 *
17 * @param props - The `persistedClient` that failed to save.
18 * @returns A copy of the client without its oldest query, or `undefined` if it
19 * has no queries.
20 */
21export const removeOldestQuery: PersistRetryer = ({ persistedClient }) => {
22 const mutations = [...persistedClient.clientState.mutations]
23 const queries = [...persistedClient.clientState.queries]
24 const client: PersistedClient = {
25 ...persistedClient,
26 clientState: { mutations, queries },
27 }
28​
29 // sort queries by dataUpdatedAt (oldest first)
30 const sortedQueries = [...queries].sort(
31 (a, b) => a.state.dataUpdatedAt - b.state.dataUpdatedAt,
32 )
33​
34 // clean oldest query
35 if (sortedQueries.length > 0) {
36 const oldestData = sortedQueries.shift()
37 client.clientState.queries = queries.filter((q) => q !== oldestData)
38 return client
39 }
40​
41 return undefined