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

providers.ts

203 lines6.6 KB

1import { isPlatformServer } from '@angular/common'
2import {
3 DestroyRef,
4 InjectionToken,
5 PLATFORM_ID,
6 TransferState,
7 inject,
8 makeEnvironmentProviders,
9 makeStateKey,
10 provideEnvironmentInitializer,
11} from '@angular/core'
12import type { EnvironmentProviders } from '@angular/core'
13import {
14 QueryClient,
15 dehydrate,
16 hydrate,
17 type DehydratedState,
18} from '@tanstack/query-core'
19import { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from './hydration-state-key'
20​
21function configureQueryClientTransferState() {
22 const queryClient = inject(QueryClient)
23 const destroyRef = inject(DestroyRef)
24 const transferState = inject(TransferState)
25 const platformId = inject(PLATFORM_ID)
26 const hydrationStateKey = inject(INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY)
27​
28 if (isPlatformServer(platformId)) {
29 transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient))
30 }
31​
32 const dehydratedState = transferState.get(hydrationStateKey, null)
33 if (dehydratedState) {
34 hydrate(queryClient, dehydratedState)
35 transferState.remove(hydrationStateKey)
36 }
37​
38 queryClient.mount()
39 destroyRef.onDestroy(() => queryClient.unmount())
41​
42/**
43 * Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the
44 * {@link https://tanstack.com/query/latest/docs/reference/QueryClient|QueryClient}
45 * for the entire application. Internally it calls `provideQueryClient`.
46 * You can use `provideQueryClient` to provide a different `QueryClient` instance for a part
47 * of the application or for unit testing purposes.
48 *
49 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
50 * @returns A single {@link EnvironmentProviders} value to add to environment `providers` (do not spread).
51 */
52export function provideQueryClient(
53 queryClient: QueryClient | InjectionToken<QueryClient>,
54): EnvironmentProviders {
55 return makeEnvironmentProviders([
56 queryClient instanceof InjectionToken
57 ? { provide: QueryClient, useExisting: queryClient }
58 : { provide: QueryClient, useValue: queryClient },
59 provideEnvironmentInitializer(configureQueryClientTransferState),
60 ])
62​
63/**
64 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
65 *
66 * Allows to configure a `QueryClient` and optional features such as developer tools.
67 *
68 * **Example - standalone**
69 *
70 * ```ts
71 * import {
72 * provideTanStackQuery,
73 * QueryClient,
74 * } from '@tanstack/angular-query-experimental'
75 *
76 * bootstrapApplication(AppComponent, {
77 * providers: [provideTanStackQuery(new QueryClient())],
78 * })
79 * ```
80 *
81 * **Example - NgModule-based**
82 *
83 * ```ts
84 * import {
85 * provideTanStackQuery,
86 * QueryClient,
87 * } from '@tanstack/angular-query-experimental'
88 *
89 * @NgModule({
90 * declarations: [AppComponent],
91 * imports: [BrowserModule],
92 * providers: [provideTanStackQuery(new QueryClient())],
93 * bootstrap: [AppComponent],
94 * })
95 * export class AppModule {}
96 * ```
97 *
98 * ```ts
99 * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'
100 * import { withDevtools } from '@tanstack/angular-query-devtools'
101 *
102 * bootstrapApplication(AppComponent, {
103 * providers: [provideTanStackQuery(new QueryClient(), withDevtools())],
104 * })
105 * ```
106 *
107 * **Example: using an InjectionToken**
108 *
109 * ```ts
110 * export const MY_QUERY_CLIENT = new InjectionToken('', {
111 * factory: () => new QueryClient(),
112 * })
113 *
114 * providers: [provideTanStackQuery(MY_QUERY_CLIENT)]
115 * ```
116 *
117 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
118 * @param features - Optional features to configure additional Query functionality.
119 * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).
120 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
121 * @see https://tanstack.com/query/v5/docs/framework/angular/devtools
122 * @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr
123 */
124export function provideTanStackQuery(
125 queryClient: QueryClient | InjectionToken<QueryClient>,
126 ...features: Array<QueryFeatures>
127): EnvironmentProviders {
128 return makeEnvironmentProviders([
129 provideQueryClient(queryClient),
130 ...features.flatMap((feature) => feature.ɵproviders),
131 ])
133​
134type QueryFeatureKind = 'Devtools' | 'Hydration' | 'PersistQueryClient'
135​
136/**
137 * Helper type to represent a Query feature.
138 */
139export interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
140 ɵkind: TFeatureKind
141 ɵproviders: EnvironmentProviders
143​
144/**
145 * Helper function to create an object that represents a Query feature.
146 * @param kind - The feature kind identifier.
147 * @param providers - The providers contributed by the feature.
148 * @returns A Query feature.
149 */
150export function queryFeature<TFeatureKind extends QueryFeatureKind>(
151 kind: TFeatureKind,
152 providers: EnvironmentProviders,
153): QueryFeature<TFeatureKind> {
154 return { ɵkind: kind, ɵproviders: providers }
156​
157/**
158 * A type alias that represents a feature which enables developer tools.
159 * The type is used to describe the return value of the `withDevtools` function.
160 * @see {@link withDevtools}
161 */
162export type DevtoolsFeature = QueryFeature<'Devtools'>
163​
164/**
165 * A type alias that represents a feature which enables persistence.
166 * The type is used to describe the return value of the `withPersistQueryClient` function.
167 */
168export type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>
169​
170/**
171 * Sets a non-default serialization key for this injector’s `QueryClient` cache (server dehydrate /
172 * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances
173 * so each has its own key. The default key applies when you do not add this feature.
174 *
175 * ```ts
176 * providers: [
177 * provideTanStackQuery(secondaryClient, withHydrationKey('my-secondary-query-cache')),
178 * ]
179 * ```
180 *
181 * @param key - A unique string for this client’s `TransferState` entry.
182 * @public
183 */
184export function withHydrationKey(key: string): QueryFeature<'Hydration'> {
185 return queryFeature('Hydration', makeEnvironmentProviders([
186 {
187 provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
188 useValue: makeStateKey<DehydratedState>(key),
189 },
190 ]))
192​
193/**
194 * A type alias that represents all Query features available for use with `provideTanStackQuery`.
195 * Features can be enabled by adding special functions to the `provideTanStackQuery` call.
196 * See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`
197 * documentation on how to use those functions.
198 * @see {@link provideTanStackQuery}
199 */
200export type QueryFeatures =
201 | DevtoolsFeature
202 | QueryFeature<'Hydration'>
203 | PersistQueryClientFeature