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

providers.ts

260 lines8.6 KB

1import { isPlatformBrowser, isPlatformServer } from '@angular/common'
2import {
3 DOCUMENT,
4 DestroyRef,
5 ENVIRONMENT_INITIALIZER,
6 InjectionToken,
7 PLATFORM_ID,
8 TransferState,
9 inject,
10 makeStateKey,
11} from '@angular/core'
12import {
14 QueryClient,
15 dehydrate,
16 hydrate
17} from '@tanstack/query-core'
18import { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from './hydration-state-key'
19import type {DehydratedState} from '@tanstack/query-core';
20import type { Provider } from '@angular/core'
21​
22const INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE = new InjectionToken<boolean>('', {
23 providedIn: 'root',
24 factory: () => true,
25})
26​
27function configureQueryClient() {
28 const queryClient = inject(QueryClient)
29 const destroyRef = inject(DestroyRef)
30 const platformId = inject(PLATFORM_ID)
31 const shouldHydrate = inject(INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE)
32 const hydrationStateKey = inject(INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY)
33​
34 if (inject(DOCUMENT, { optional: true })) {
35 const transferState = inject(TransferState)
36​
37 if (shouldHydrate && isPlatformServer(platformId)) {
38 transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient))
39 } else if (shouldHydrate && isPlatformBrowser(platformId)) {
40 const dehydratedState = transferState.get(hydrationStateKey, null)
41 if (dehydratedState) {
42 hydrate(queryClient, dehydratedState)
43 transferState.remove(hydrationStateKey)
44 }
45 }
46 }
47​
48 queryClient.mount()
49 destroyRef.onDestroy(() => queryClient.unmount())
51​
52const queryClientInitializerProvider: Provider = {
53 provide: ENVIRONMENT_INITIALIZER,
54 multi: true,
55 useValue: configureQueryClient,
57​
58function createQueryClientProviders(
59 queryClient: QueryClient | InjectionToken<QueryClient>,
60): Array<Provider> {
61 return [
62 queryClient instanceof InjectionToken
63 ? { provide: QueryClient, useExisting: queryClient }
64 : { provide: QueryClient, useValue: queryClient },
65 ]
67​
68/**
69 * Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the
70 * {@link https://tanstack.com/query/latest/docs/reference/QueryClient|QueryClient}
71 * for the entire application. Internally it calls `provideQueryClient`.
72 * You can use `provideQueryClient` to provide a different `QueryClient` instance for a part
73 * of the application or for unit testing purposes.
74 *
75 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
76 * @returns Providers to register with the spread operator, e.g. `providers: [...provideQueryClient(client)]`.
77 */
78export function provideQueryClient(
79 queryClient: QueryClient | InjectionToken<QueryClient>,
80): Array<Provider> {
81 return [...createQueryClientProviders(queryClient), queryClientInitializerProvider]
83​
84/**
85 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
86 *
87 * Allows to configure a `QueryClient` and optional features such as developer tools.
88 *
89 * **Example - standalone**
90 *
91 * ```ts
92 * import {
93 * provideTanStackQuery,
94 * QueryClient,
95 * } from '@tanstack/angular-query-experimental'
96 *
97 * bootstrapApplication(AppComponent, {
98 * providers: [...provideTanStackQuery(new QueryClient())],
99 * })
100 * ```
101 *
102 * **Example - NgModule-based**
103 *
104 * ```ts
105 * import {
106 * provideTanStackQuery,
107 * QueryClient,
108 * } from '@tanstack/angular-query-experimental'
109 *
110 * @NgModule({
111 * declarations: [AppComponent],
112 * imports: [BrowserModule],
113 * providers: [...provideTanStackQuery(new QueryClient())],
114 * bootstrap: [AppComponent],
115 * })
116 * export class AppModule {}
117 * ```
118 *
119 * You can also enable optional developer tools by adding `withDevtools`. By
120 * default the tools will then be loaded when your app is in development mode.
121 *
122 * ```ts
123 * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'
124 * import { withDevtools } from '@tanstack/angular-query-devtools'
125 *
126 * bootstrapApplication(AppComponent, {
127 * providers: [...provideTanStackQuery(new QueryClient(), withDevtools())],
128 * })
129 * ```
130 *
131 * **Example: using an InjectionToken**
132 *
133 * ```ts
134 * export const MY_QUERY_CLIENT = new InjectionToken('', {
135 * factory: () => new QueryClient(),
136 * })
137 *
138 * // In a lazy loaded route or lazy loaded component's providers array:
139 * providers: [...provideTanStackQuery(MY_QUERY_CLIENT)]
140 * ```
141 * Using an InjectionToken for the QueryClient is an advanced optimization which allows TanStack Query to be absent from the main application bundle.
142 * This can be beneficial if you want to include TanStack Query on lazy loaded routes only while still sharing a `QueryClient`.
143 *
144 * Note that this is a small optimization and for most applications it's preferable to provide the `QueryClient` in the main application config.
145 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
146 * @param features - Optional features to configure additional Query functionality.
147 * @returns A set of providers to set up TanStack Query (spread into `providers`).
148 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
149 * @see https://tanstack.com/query/v5/docs/framework/angular/devtools
150 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr
151 */
152export function provideTanStackQuery(
153 queryClient: QueryClient | InjectionToken<QueryClient>,
154 ...features: Array<QueryFeatures>
155): Array<Provider> {
156 return [
157 ...createQueryClientProviders(queryClient),
158 ...features.flatMap((feature) => feature.ɵproviders),
159 queryClientInitializerProvider,
160 ]
162​
163/**
164 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
165 *
166 * Allows to configure a `QueryClient`.
167 * @param queryClient - A `QueryClient` instance.
168 * @returns A set of providers to set up TanStack Query.
169 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
170 * @deprecated Use `provideTanStackQuery` instead.
171 */
172export function provideAngularQuery(
173 queryClient: QueryClient,
174): Array<Provider> {
175 return provideTanStackQuery(queryClient)
177​
178const queryFeatures = ['Devtools', 'Hydration', 'PersistQueryClient'] as const
179​
180type QueryFeatureKind = (typeof queryFeatures)[number]
181​
182/**
183 * Helper type to represent a Query feature.
184 */
185export interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
186 ɵkind: TFeatureKind
187 ɵproviders: Array<Provider>
189​
190/**
191 * Helper function to create an object that represents a Query feature.
192 * @param kind -
193 * @param providers -
194 * @returns A Query feature.
195 */
196export function queryFeature<TFeatureKind extends QueryFeatureKind>(
197 kind: TFeatureKind,
198 providers: Array<Provider>,
199): QueryFeature<TFeatureKind> {
200 return { ɵkind: kind, ɵproviders: providers }
202​
203/**
204 * A type alias that represents a feature which enables developer tools.
205 * The type is used to describe the return value of the `withDevtools` function.
206 * @see {@link withDevtools}
207 */
208export type DevtoolsFeature = QueryFeature<'Devtools'>
209​
210/**
211 * A type alias that represents a feature which enables persistence.
212 * The type is used to describe the return value of the `withPersistQueryClient` function.
213 */
214export type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>
215​
216/**
217 * Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /
218 * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances
219 * so each has its own key. The default key applies when you do not add this feature.
220 *
221 * ```ts
222 * providers: [
223 * ...provideTanStackQuery(secondaryClient, withHydrationKey('my-secondary-query-cache')),
224 * ]
225 * ```
226 *
227 * @param key - A unique string for this client's `TransferState` entry.
228 */
229export function withHydrationKey(key: string): QueryFeature<'Hydration'> {
230 return queryFeature('Hydration', [
231 {
232 provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
233 useValue: makeStateKey<DehydratedState>(key),
234 },
235 ])
237​
238/**
239 * Disables `TransferState` hydration and dehydration for the current environment injector.
240 */
241export function withNoQueryHydration(): QueryFeature<'Hydration'> {
242 return queryFeature('Hydration', [
243 {
244 provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,
245 useValue: false,
246 },
247 ])
249​
250/**
251 * A type alias that represents all Query features available for use with `provideTanStackQuery`.
252 * Features can be enabled by adding special functions to the `provideTanStackQuery` call.
253 * See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`
254 * documentation on how to use those functions.
255 * @see {@link provideTanStackQuery}
256 */
257export type QueryFeatures =
258 | DevtoolsFeature
259 | QueryFeature<'Hydration'>
260 | PersistQueryClientFeature