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

providers.ts

368 lines11.9 KB

1import {
2 DestroyRef,
3 ENVIRONMENT_INITIALIZER,
4 InjectionToken,
5 PLATFORM_ID,
6 computed,
7 effect,
8 inject,
9} from '@angular/core'
10import { QueryClient, noop, onlineManager } from '@tanstack/query-core'
11import { isPlatformBrowser } from '@angular/common'
12import { isDevMode } from './util/is-dev-mode/is-dev-mode'
13import type { Provider } from '@angular/core'
14import type {
15 DevtoolsButtonPosition,
16 DevtoolsErrorType,
17 DevtoolsPosition,
18 TanstackQueryDevtools,
19} from '@tanstack/query-devtools'
20​
21/**
22 * Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the
23 * {@link https://tanstack.com/query/latest/docs/reference/QueryClient|QueryClient}
24 * for the entire application. Internally it calls `provideQueryClient`.
25 * You can use `provideQueryClient` to provide a different `QueryClient` instance for a part
26 * of the application or for unit testing purposes.
27 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
28 * @returns a provider object that can be used to provide the `QueryClient` instance.
29 */
30export function provideQueryClient(
31 queryClient: QueryClient | InjectionToken<QueryClient>,
32): Provider {
33 return {
34 provide: QueryClient,
35 useFactory: () => {
36 const client =
37 queryClient instanceof InjectionToken
38 ? inject(queryClient)
39 : queryClient
40 // Unmount the query client on injector destroy
41 inject(DestroyRef).onDestroy(() => client.unmount())
42 client.mount()
43 return client
44 },
45 }
47​
48/**
49 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
50 *
51 * Allows to configure a `QueryClient` and optional features such as developer tools.
52 *
53 * **Example - standalone**
54 *
55 * ```ts
56 * import {
57 * provideTanStackQuery,
58 * QueryClient,
59 * } from '@tanstack/angular-query-experimental'
60 *
61 * bootstrapApplication(AppComponent, {
62 * providers: [provideTanStackQuery(new QueryClient())],
63 * })
64 * ```
65 *
66 * **Example - NgModule-based**
67 *
68 * ```ts
69 * import {
70 * provideTanStackQuery,
71 * QueryClient,
72 * } from '@tanstack/angular-query-experimental'
73 *
74 * @NgModule({
75 * declarations: [AppComponent],
76 * imports: [BrowserModule],
77 * providers: [provideTanStackQuery(new QueryClient())],
78 * bootstrap: [AppComponent],
79 * })
80 * export class AppModule {}
81 * ```
82 *
83 * You can also enable optional developer tools by adding `withDevtools`. By
84 * default the tools will then be loaded when your app is in development mode.
85 * ```ts
86 * import {
87 * provideTanStackQuery,
88 * withDevtools
89 * QueryClient,
90 * } from '@tanstack/angular-query-experimental'
91 *
92 * bootstrapApplication(AppComponent,
93 * {
94 * providers: [
95 * provideTanStackQuery(new QueryClient(), withDevtools())
96 * ]
97 * }
98 * )
99 * ```
100 *
101 * **Example: using an InjectionToken**
102 *
103 * ```ts
104 * export const MY_QUERY_CLIENT = new InjectionToken('', {
105 * factory: () => new QueryClient(),
106 * })
107 *
108 * // In a lazy loaded route or lazy loaded component's providers array:
109 * providers: [provideTanStackQuery(MY_QUERY_CLIENT)]
110 * ```
111 * @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
112 * @param features - Optional features to configure additional Query functionality.
113 * @returns A set of providers to set up TanStack Query.
114 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
115 * @see withDevtools
116 */
117export function provideTanStackQuery(
118 queryClient: QueryClient | InjectionToken<QueryClient>,
119 ...features: Array<QueryFeatures>
120): Array<Provider> {
121 return [
122 provideQueryClient(queryClient),
123 features.map((feature) => feature.ɵproviders),
124 ]
126​
127/**
128 * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
129 *
130 * Allows to configure a `QueryClient`.
131 * @param queryClient - A `QueryClient` instance.
132 * @returns A set of providers to set up TanStack Query.
133 * @public
134 * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
135 * @deprecated Use `provideTanStackQuery` instead.
136 */
137export function provideAngularQuery(queryClient: QueryClient): Array<Provider> {
138 return provideTanStackQuery(queryClient)
140​
141/**
142 * Helper type to represent a Query feature.
143 */
144export interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
145 ɵkind: TFeatureKind
146 ɵproviders: Array<Provider>
148​
149/**
150 * Helper function to create an object that represents a Query feature.
151 * @param kind -
152 * @param providers -
153 * @returns A Query feature.
154 */
155export function queryFeature<TFeatureKind extends QueryFeatureKind>(
156 kind: TFeatureKind,
157 providers: Array<Provider>,
158): QueryFeature<TFeatureKind> {
159 return { ɵkind: kind, ɵproviders: providers }
161​
162/**
163 * A type alias that represents a feature which enables developer tools.
164 * The type is used to describe the return value of the `withDevtools` function.
165 * @public
166 * @see {@link withDevtools}
167 */
168export type DeveloperToolsFeature = QueryFeature<'DeveloperTools'>
169​
170/**
171 * A type alias that represents a feature which enables persistence.
172 * The type is used to describe the return value of the `withPersistQueryClient` function.
173 * @public
174 */
175export type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>
176​
177/**
178 * Options for configuring the TanStack Query devtools.
179 * @public
180 */
181export interface DevtoolsOptions {
182 /**
183 * Set this true if you want the devtools to default to being open
184 */
185 initialIsOpen?: boolean
186 /**
187 * The position of the TanStack logo to open and close the devtools panel.
188 * `top-left` | `top-right` | `bottom-left` | `bottom-right` | `relative`
189 * Defaults to `bottom-right`.
190 */
191 buttonPosition?: DevtoolsButtonPosition
192 /**
193 * The position of the TanStack Query devtools panel.
194 * `top` | `bottom` | `left` | `right`
195 * Defaults to `bottom`.
196 */
197 position?: DevtoolsPosition
198 /**
199 * Custom instance of QueryClient
200 */
201 client?: QueryClient
202 /**
203 * Use this so you can define custom errors that can be shown in the devtools.
204 */
205 errorTypes?: Array<DevtoolsErrorType>
206 /**
207 * Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
208 */
209 styleNonce?: string
210 /**
211 * Use this so you can attach the devtool's styles to a specific element in the DOM.
212 */
213 shadowDOMTarget?: ShadowRoot
214​
215 /**
216 * Whether the developer tools should load.
217 * - `auto`- (Default) Lazily loads devtools when in development mode. Skips loading in production mode.
218 * - `true`- Always load the devtools, regardless of the environment.
219 * - `false`- Never load the devtools, regardless of the environment.
220 *
221 * You can use `true` and `false` to override loading developer tools from an environment file.
222 * For example, a test environment might run in production mode but you may want to load developer tools.
223 *
224 * Additionally, you can use a signal in the callback to dynamically load the devtools based on a condition. For example,
225 * a signal created from a RxJS observable that listens for a keyboard shortcut.
226 *
227 * **Example**
228 * ```ts
229 * withDevtools(() => ({
230 * initialIsOpen: true,
231 * loadDevtools: inject(ExampleService).loadDevtools()
232 * }))
233 * ```
234 */
235 loadDevtools?: 'auto' | boolean
237​
238/**
239 * Enables developer tools.
240 *
241 * **Example**
242 *
243 * ```ts
244 * export const appConfig: ApplicationConfig = {
245 * providers: [
246 * provideTanStackQuery(new QueryClient(), withDevtools())
247 * ]
248 * }
249 * ```
250 * By default the devtools will be loaded when Angular runs in development mode and rendered in `<body>`.
251 *
252 * If you need more control over when devtools are loaded, you can use the `loadDevtools` option. This is particularly useful if you want to load devtools based on environment configurations. For instance, you might have a test environment running in production mode but still require devtools to be available.
253 *
254 * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
255 * @param withDevtoolsFn - A function that returns `DevtoolsOptions`.
256 * @returns A set of providers for use with `provideTanStackQuery`.
257 * @public
258 * @see {@link provideTanStackQuery}
259 * @see {@link DevtoolsOptions}
260 */
261export function withDevtools(
262 withDevtoolsFn?: () => DevtoolsOptions,
263): DeveloperToolsFeature {
264 let providers: Array<Provider> = []
265 if (!isDevMode() && !withDevtoolsFn) {
266 providers = []
267 } else {
268 providers = [
269 {
270 // Do not use provideEnvironmentInitializer while Angular < v19 is supported
271 provide: ENVIRONMENT_INITIALIZER,
272 multi: true,
273 useFactory: () => {
274 if (!isPlatformBrowser(inject(PLATFORM_ID))) return noop
275 const injectedClient = inject(QueryClient, {
276 optional: true,
277 })
278 const destroyRef = inject(DestroyRef)
279​
280 const options = computed(() => withDevtoolsFn?.() ?? {})
281​
282 let devtools: TanstackQueryDevtools | null = null
283 let el: HTMLElement | null = null
284​
285 const shouldLoadToolsSignal = computed(() => {
286 const { loadDevtools } = options()
287 return typeof loadDevtools === 'boolean'
288 ? loadDevtools
289 : isDevMode()
290 })
291​
292 const getResolvedQueryClient = () => {
293 const client = options().client ?? injectedClient
294 if (!client) {
295 throw new Error('No QueryClient found')
296 }
297 return client
298 }
299​
300 const destroyDevtools = () => {
301 devtools?.unmount()
302 el?.remove()
303 devtools = null
304 }
305​
306 return () =>
307 effect(() => {
308 const shouldLoadTools = shouldLoadToolsSignal()
309 const {
310 client,
311 position,
312 errorTypes,
313 buttonPosition,
314 initialIsOpen,
315 } = options()
316​
317 if (devtools && !shouldLoadTools) {
318 destroyDevtools()
319 return
320 } else if (devtools && shouldLoadTools) {
321 client && devtools.setClient(client)
322 position && devtools.setPosition(position)
323 errorTypes && devtools.setErrorTypes(errorTypes)
324 buttonPosition && devtools.setButtonPosition(buttonPosition)
325 initialIsOpen && devtools.setInitialIsOpen(initialIsOpen)
326 return
327 } else if (!shouldLoadTools) {
328 return
329 }
330​
331 el = document.body.appendChild(document.createElement('div'))
332 el.classList.add('tsqd-parent-container')
333​
334 import('@tanstack/query-devtools').then((queryDevtools) => {
335 devtools = new queryDevtools.TanstackQueryDevtools({
336 ...options(),
337 client: getResolvedQueryClient(),
338 queryFlavor: 'Angular Query',
339 version: '5',
340 onlineManager,
341 })
342​
343 el && devtools.mount(el)
344​
345 // Unmount the devtools on application destroy
346 destroyRef.onDestroy(destroyDevtools)
347 })
348 })
349 },
350 },
351 ]
352 }
353 return queryFeature('DeveloperTools', providers)
355​
356/**
357 * A type alias that represents all Query features available for use with `provideTanStackQuery`.
358 * Features can be enabled by adding special functions to the `provideTanStackQuery` call.
359 * See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`
360 * documentation on how to use those functions.
361 * @public
362 * @see {@link provideTanStackQuery}
363 */
364export type QueryFeatures = DeveloperToolsFeature | PersistQueryClientFeature
365​
366export const queryFeatures = ['DeveloperTools', 'PersistQueryClient'] as const
367​
368export type QueryFeatureKind = (typeof queryFeatures)[number]