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

providers.ts

349 lines11.1 KB

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