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