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

providers.ts

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