Open History to see the last commit
1import {
2 QueryClient,
3 provideIsRestoring,
4 queryFeature,
5} from '@tanstack/angular-query-experimental'
6import {
7 DestroyRef,
8 PLATFORM_ID,
9 inject,
10 makeEnvironmentProviders,
11 provideEnvironmentInitializer,
12 signal,
13} from '@angular/core'
14import { isPlatformBrowser } from '@angular/common'
15import {
16 persistQueryClientRestore,
17 persistQueryClientSubscribe,
18} from '@tanstack/query-persist-client-core'
19import type { PersistQueryClientFeature } from '@tanstack/angular-query-experimental'
20import type {
21 PersistQueryClientUserOptions,
22 WithPersistQueryClientFn,
23 WithPersistQueryClientOptions,
24} from './with-persist-query-client.types'
25β
26export type {
27 PersistQueryClientUserOptions,
28 WithPersistQueryClientFn,
29 WithPersistQueryClientOptions,
30} from './with-persist-query-client.types'
31β
32/**
33 * @param input - Static options object or factory callback
34 * @param withOptions - When `input` is a function, optional `deps` for injection
35 * @param injectDep - `inject` from the current initializer context
36 * @returns Resolved persistence options
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
49}
50β
51/**
52 * Enables persistence.
53 * **Example (static options)** β avoid browser-only globals at module scope when the same config runs on the server; prefer the factory form below for `localStorage`.
54 *
55 * ```ts
56 * withPersistQueryClient({
57 * persistOptions: { persister },
58 * onSuccess: () => console.log('Restored.'),
59 * })
60 * ```
61 *
62 * **Example (factory, browser only, optional deps)** β same as `withDevtools`: the function runs only in the browser, so you can safely use `localStorage`.
63 *
64 * ```ts
65 * withPersistQueryClient(() => ({
66 * persistOptions: {
67 * persister: createAsyncStoragePersister({ storage: localStorage }),
68 * },
69 * }))
70 * ```
71 *
72 * ```ts
73 * withPersistQueryClient(
74 * (storage: StorageService) => ({
75 * persistOptions: { persister: storage.createPersister() },
76 * }),
77 * { deps: [StorageService] },
78 * )
79 * ```
80 * @param factoryOrOptions - Either a callback (runs only in the browser) or a static options object.
81 * @param withOptions - When using a callback, optional `deps` passed as arguments (like `useFactory`).
82 * @returns A set of providers for use with `provideTanStackQuery`.
83 * @public
84 */
85export function withPersistQueryClient(
86 factoryOrOptions: WithPersistQueryClientFn,
87 withOptions?: WithPersistQueryClientOptions,
88): PersistQueryClientFeature
89export function withPersistQueryClient(
90 options: PersistQueryClientUserOptions,
91): PersistQueryClientFeature
92/**
93 * @param factoryOrOptions - See overload documentation.
94 * @param withOptions - See overload documentation.
95 * @returns Persist query client feature providers.
96 */
97export function withPersistQueryClient(
98 factoryOrOptions:
99 | PersistQueryClientUserOptions
100 | WithPersistQueryClientFn,
101 withOptions?: WithPersistQueryClientOptions,
102): PersistQueryClientFeature {
103 const isRestoring = signal(true)
104 return queryFeature('PersistQueryClient', makeEnvironmentProviders([
105 provideIsRestoring(isRestoring.asReadonly()),
106 provideEnvironmentInitializer(() => {
107 if (!isPlatformBrowser(inject(PLATFORM_ID))) {
108 isRestoring.set(false)
109 return
110 }
111β
112 const destroyRef = inject(DestroyRef)
113 const queryClient = inject(QueryClient)
114β
115 const { onSuccess, onError, persistOptions } = resolvePersistOptions(
116 factoryOrOptions,
117 withOptions,
118 inject,
119 )
120β
121 const options = { queryClient, ...persistOptions }
122β
123 void persistQueryClientRestore(options).then(() => {
124 return onSuccess?.()
125 }).catch(() => {
126 return onError?.()
127 }).finally(() => {
128 if (destroyRef.destroyed) return
129β
130 isRestoring.set(false)
131 const cleanup = persistQueryClientSubscribe(options)
132 destroyRef.onDestroy(cleanup)
133 })
134 }),
135 ]))
136}