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

providers.ts

192 lines5.9 KB

1import { isPlatformBrowser, isPlatformServer } from '@angular/common'
2import {
3 DOCUMENT,
4 DestroyRef,
5 InjectionToken,
6 PLATFORM_ID,
7 TransferState,
8 inject,
9 makeEnvironmentProviders,
10 makeStateKey,
11 provideEnvironmentInitializer,
12} from '@angular/core'
13import { QueryClient, dehydrate, hydrate } from '@tanstack/query-core'
14import { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from './hydration-state-key'
15import { injectQueryZone } from './utils/inject-query-zone'
16import type { DehydratedState } from '@tanstack/query-core'
17import type { EnvironmentProviders } from '@angular/core'
18​
19const INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE = new InjectionToken<boolean>('', {
20 providedIn: 'root',
21 factory: () => true,
22})
23​
24function configureQueryClient() {
25 const queryClient = inject(QueryClient)
26 const destroyRef = inject(DestroyRef)
27 const platformId = inject(PLATFORM_ID)
28​
29 if (isPlatformServer(platformId)) {
30 // DOM emulation can fool core's runtime detection. Apply server defaults to
31 // this client without changing other clients or global scheduling providers.
32 const defaults = queryClient.getDefaultOptions()
33 queryClient.setDefaultOptions({
34 ...defaults,
35 queries: { gcTime: Infinity, retry: false, ...defaults.queries },
36 mutations: { gcTime: Infinity, ...defaults.mutations },
37 })
38 }
39 const shouldHydrate = inject(INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE)
40 const hydrationStateKey = inject(
41 INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
42 )
43​
44 if (inject(DOCUMENT, { optional: true })) {
45 const transferState = inject(TransferState)
46​
47 if (shouldHydrate && isPlatformServer(platformId)) {
48 transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient))
49 } else if (shouldHydrate && isPlatformBrowser(platformId)) {
50 const dehydratedState = transferState.get(hydrationStateKey, null)
51 if (dehydratedState) {
52 hydrate(queryClient, dehydratedState)
53 transferState.remove(hydrationStateKey)
54 }
55 }
56 }
57​
58 queryClient.mount()
59 destroyRef.onDestroy(() => queryClient.unmount())
61​
62/**
63 * Provides a `QueryClient` and optional TanStack Query features.
64 * The factory runs once per injector in Angular's injection context, so it can
65 * call `inject()` and each SSR request can receive an independent cache.
66 *
67 * **Example - standalone**
68 *
69 * @example
70 * ```ts
71 * import {
72 * provideTanStackQuery,
73 * QueryClient,
74 * } from '@tanstack/angular-query'
75 *
76 * bootstrapApplication(AppComponent, {
77 * providers: [provideTanStackQuery(() => new QueryClient())],
78 * })
79 * ```
80 *
81 * You can also enable optional developer tools by adding `withDevtools`. By
82 * default the tools will then be loaded when your app is in development mode.
83 *
84 * ```ts
85 * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
86 * import { withDevtools } from '@tanstack/angular-query-devtools'
87 *
88 * bootstrapApplication(AppComponent, {
89 * providers: [
90 * provideTanStackQuery(() => new QueryClient(), withDevtools()),
91 * ],
92 * })
93 * ```
94 *
95 * @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.
96 * @param features - Optional features to configure additional Query functionality.
97 * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).
98 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
99 * @see https://tanstack.com/query/v5/docs/framework/angular/devtools
100 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr
101 */
102export function provideTanStackQuery(
103 queryClientFactory: () => QueryClient,
104 ...features: ReadonlyArray<QueryFeature>
105): EnvironmentProviders {
106 return makeEnvironmentProviders([
107 {
108 provide: QueryClient,
109 useFactory: () => injectQueryZone()(queryClientFactory),
110 },
111 ...features.map(getQueryFeatureProviders),
112 provideEnvironmentInitializer(configureQueryClient),
113 ])
115​
116const queryFeatureBrand: unique symbol = Symbol('QueryFeature')
117​
118/**
119 * Opaque configuration returned by Query feature functions such as `withHydrationKey`.
120 * Pass features to `provideTanStackQuery`; applications do not construct them directly.
121 */
122export interface QueryFeature {
123 /** @internal */
124 readonly [queryFeatureBrand]: true
126​
127interface InternalQueryFeature extends QueryFeature {
128 readonly ɵproviders: EnvironmentProviders
130​
131/**
132 * Creates a feature shared by Angular Query integration packages.
133 * @internal
134 * @param providers -
135 * @returns A Query feature.
136 */
137export function queryFeature(providers: EnvironmentProviders): QueryFeature {
138 const feature: InternalQueryFeature = {
139 [queryFeatureBrand]: true,
140 ɵproviders: providers,
141 }
142​
143 return feature
145​
146/** @internal */
147export function getQueryFeatureProviders(
148 feature: QueryFeature,
149): EnvironmentProviders {
150 return (feature as InternalQueryFeature).ɵproviders
152​
153/**
154 * Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /
155 * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances
156 * so each has its own key. The default key applies when you do not add this feature.
157 *
158 * ```ts
159 * providers: [
160 * provideTanStackQuery(
161 * () => new QueryClient(),
162 * withHydrationKey('my-secondary-query-cache'),
163 * ),
164 * ]
165 * ```
166 *
167 * @param key - A unique string for this client's `TransferState` entry.
168 */
169export function withHydrationKey(key: string): QueryFeature {
170 return queryFeature(
171 makeEnvironmentProviders([
172 {
173 provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
174 useValue: makeStateKey<DehydratedState>(key),
175 },
176 ]),
177 )
179​
180/**
181 * Disables `TransferState` hydration and dehydration for the current environment injector.
182 */
183export function withNoQueryHydration(): QueryFeature {
184 return queryFeature(
185 makeEnvironmentProviders([
186 {
187 provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,
188 useValue: false,
189 },
190 ]),
191 )