Open History to see the last commit
1import { isPlatformBrowser } from '@angular/common'
2import {
3 DestroyRef,
4 InjectionToken,
5 PLATFORM_ID,
6 inject,
7 makeEnvironmentProviders,
8 provideEnvironmentInitializer,
9 signal,
10} from '@angular/core'
11import { QueryClient } from '@tanstack/angular-query'
12import {
13 provideIsRestoring,
14 queryFeature,
15} from '@tanstack/angular-query/internal'
16import {
17 persistQueryClientRestore,
18 persistQueryClientSubscribe,
19} from '@tanstack/query-persist-client-core'
20import type { WritableSignal } from '@angular/core'
21import type { QueryFeature } from '@tanstack/angular-query'
22import type { WithPersistQueryClientFn } from './with-persist-query-client.types'
23β
24const RESTORING_STATE = new InjectionToken<WritableSignal<boolean>>(
25 'Query restoration state',
26)
27β
28export type {
29 PersistQueryClientUserOptions,
30 WithPersistQueryClientFn,
31} from './with-persist-query-client.types'
32β
33/**
34 * Enables persistence. The options factory runs once per injector, only in the
35 * browser, in an Angular injection context. It can call `inject()` and use
36 * browser APIs such as `localStorage`.
37 *
38 * ```ts
39 * export const appConfig: ApplicationConfig = {
40 * providers: [
41 * provideTanStackQuery(
42 * () => new QueryClient(),
43 * withPersistQueryClient(() => ({
44 * persistOptions: {
45 * persister: createAsyncStoragePersister({ storage: localStorage }),
46 * },
47 * onSuccess: () => console.log('Restoration completed successfully.'),
48 * })),
49 * ),
50 * ],
51 * }
52 * ```
53 * @param optionsFactory - Creates the persistence options in the browser, and optional `onSuccess` and
54 * `onError` callbacks which get called when the restoration process is complete.
55 * @returns A set of providers for use with `provideTanStackQuery`.
56 * @public
57 */
58export function withPersistQueryClient(
59 optionsFactory: WithPersistQueryClientFn,
60): QueryFeature {
61 return queryFeature(
62 makeEnvironmentProviders([
63 { provide: RESTORING_STATE, useFactory: () => signal(true) },
64 provideIsRestoring(() => inject(RESTORING_STATE).asReadonly()),
65 provideEnvironmentInitializer(() => {
66 const isRestoring = inject(RESTORING_STATE)
67 if (!isPlatformBrowser(inject(PLATFORM_ID))) {
68 isRestoring.set(false)
69 return
70 }
71 const destroyRef = inject(DestroyRef)
72 const queryClient = inject(QueryClient)
73β
74 const { onSuccess, onError, persistOptions } = optionsFactory()
75 const options = { queryClient, ...persistOptions }
76 void persistQueryClientRestore(options)
77 .then(() => {
78 return onSuccess?.()
79 })
80 .catch(() => {
81 return onError?.()
82 })
83 .finally(() => {
84 if (destroyRef.destroyed) return
85 isRestoring.set(false)
86 const cleanup = persistQueryClientSubscribe(options)
87 destroyRef.onDestroy(cleanup)
88 })
89 }),
90 ]),
91 )
92}