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

with-persist-query-client.ts

155 lines4.8 KB

1import {
2 QueryClient,
3 provideIsRestoring,
4 queryFeature,
5} from '@tanstack/angular-query-experimental'
6import {
7 DestroyRef,
8 ENVIRONMENT_INITIALIZER,
9 PLATFORM_ID,
10 inject,
11 signal,
12} from '@angular/core'
13import { isPlatformBrowser } from '@angular/common'
14import {
15 persistQueryClientRestore,
16 persistQueryClientSubscribe,
17} from '@tanstack/query-persist-client-core'
18import type { PersistQueryClientFeature } from '@tanstack/angular-query-experimental'
19import type {
20 PersistQueryClientUserOptions,
21 WithPersistQueryClientFn,
22 WithPersistQueryClientOptions,
23} from './with-persist-query-client.types'
24​
25export type {
26 PersistQueryClientUserOptions,
27 WithPersistQueryClientFn,
28 WithPersistQueryClientOptions,
29} from './with-persist-query-client.types'
30​
31/**
32 * Resolves factory vs static persistence configuration.
33 * @param input - Callback, static options object, or mixed union.
34 * @param withOptions - When `input` is a callback, optional `deps` for dependency injection.
35 * @param injectDep - `inject` function used to resolve `withOptions.deps` tokens.
36 * @returns Resolved persistence user options for the browser initializer.
37 */
38function resolvePersistOptions(
39 input: PersistQueryClientUserOptions | WithPersistQueryClientFn,
40 withOptions: WithPersistQueryClientOptions | undefined,
41 injectDep: <T>(token: any) => T,
42): PersistQueryClientUserOptions {
43 if (typeof input === 'function') {
44 const deps = withOptions?.deps ?? []
45 const depValues = deps.map((token) => injectDep(token))
46 return input(...depValues)
47 }
48 return input
50​
51/**
52 * Enables persistence.
53 *
54 * **Example (static options)** - avoid browser-only globals at module scope when the same config
55 * runs on the server; prefer the factory form below for `localStorage`.
56 *
57 * ```ts
58 * withPersistQueryClient({
59 * persistOptions: { persister },
60 * onSuccess: () => console.log('Restored.'),
61 * })
62 *
63 * export const appConfig: ApplicationConfig = {
64 * providers: [
65 * ...provideTanStackQuery(
66 * new QueryClient(),
67 * withPersistQueryClient({
68 * persistOptions: {
69 * persister: localStoragePersister,
70 * },
71 * onSuccess: () => console.log('Restoration completed successfully.'),
72 * }),
73 * ),
74 * ],
75 * };
76 * ```
77 *
78 * **Example (factory, browser only, optional deps)** - the callback only runs in the browser, so
79 * it can safely reference browser APIs such as `localStorage`.
80 *
81 * ```ts
82 * withPersistQueryClient(() => ({
83 * persistOptions: {
84 * persister: createAsyncStoragePersister({ storage: localStorage }),
85 * },
86 * }))
87 * ```
88 *
89 * ```ts
90 * withPersistQueryClient(
91 * (storage: StorageService) => ({
92 * persistOptions: { persister: storage.createPersister() },
93 * }),
94 * { deps: [StorageService] },
95 * )
96 * ```
97 * @param factoryOrOptions - Either a callback (runs only in the browser) or a static options object.
98 * @param withOptions - When using a callback, optional `deps` passed as arguments (like `useFactory`).
99 * @returns A set of providers for use with `provideTanStackQuery`.
100 * @public
101 */
102export function withPersistQueryClient(
103 factoryOrOptions: WithPersistQueryClientFn,
104 withOptions?: WithPersistQueryClientOptions,
105): PersistQueryClientFeature
106export function withPersistQueryClient(
107 options: PersistQueryClientUserOptions,
108): PersistQueryClientFeature
109/**
110 * @param factoryOrOptions - Either a callback (runs only in the browser) or a static options object.
111 * @param withOptions - When using a callback, optional `deps` passed as arguments (like `useFactory`).
112 * @returns A set of providers for use with `provideTanStackQuery`.
113 * @public
114 */
115export function withPersistQueryClient(
116 factoryOrOptions: PersistQueryClientUserOptions | WithPersistQueryClientFn,
117 withOptions?: WithPersistQueryClientOptions,
118): PersistQueryClientFeature {
119 const isRestoring = signal(true)
120 return queryFeature('PersistQueryClient', [
121 provideIsRestoring(isRestoring.asReadonly()),
122 {
123 provide: ENVIRONMENT_INITIALIZER,
124 multi: true,
125 useValue: () => {
126 if (!isPlatformBrowser(inject(PLATFORM_ID))) {
127 isRestoring.set(false)
128 return
129 }
130 const destroyRef = inject(DestroyRef)
131 const queryClient = inject(QueryClient)
132​
133 const { onSuccess, onError, persistOptions } = resolvePersistOptions(
134 factoryOrOptions,
135 withOptions,
136 inject,
137 )
138 const options = { queryClient, ...persistOptions }
139 void persistQueryClientRestore(options)
140 .then(() => {
141 return onSuccess?.()
142 })
143 .catch(() => {
144 return onError?.()
145 })
146 .finally(() => {
147 if (destroyRef.destroyed) return
148 isRestoring.set(false)
149 const cleanup = persistQueryClientSubscribe(options)
150 destroyRef.onDestroy(cleanup)
151 })
152 },
153 },
154 ])