@tanstack/angular-query-experimental 5.60.0 → 5.60.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/build/{rollup.d.ts → index.d.ts} +278 -356
  2. package/build/index.js +616 -0
  3. package/build/index.js.map +1 -0
  4. package/package.json +12 -15
  5. package/src/create-base-query.ts +119 -0
  6. package/src/index.ts +28 -0
  7. package/src/infinite-query-options.ts +125 -0
  8. package/src/inject-infinite-query.ts +119 -0
  9. package/src/inject-is-fetching.ts +50 -0
  10. package/src/inject-is-mutating.ts +49 -0
  11. package/src/inject-mutation-state.ts +99 -0
  12. package/src/inject-mutation.ts +122 -0
  13. package/src/inject-queries.ts +243 -0
  14. package/src/inject-query-client.ts +27 -0
  15. package/src/inject-query.ts +207 -0
  16. package/src/providers.ts +344 -0
  17. package/src/query-options.ts +125 -0
  18. package/src/signal-proxy.ts +46 -0
  19. package/src/test-setup.ts +12 -0
  20. package/src/types.ts +328 -0
  21. package/src/util/assert-injector/assert-injector.test.ts +74 -0
  22. package/src/util/assert-injector/assert-injector.ts +81 -0
  23. package/src/util/create-injection-token/create-injection-token.test.ts +32 -0
  24. package/src/util/create-injection-token/create-injection-token.ts +183 -0
  25. package/src/util/index.ts +13 -0
  26. package/src/util/is-dev-mode/is-dev-mode.ts +3 -0
  27. package/src/util/lazy-init/lazy-init.ts +34 -0
  28. package/src/util/lazy-signal-initializer/lazy-signal-initializer.ts +23 -0
  29. package/build/README.md +0 -133
  30. package/build/esm2022/create-base-query.mjs +0 -62
  31. package/build/esm2022/index.mjs +0 -16
  32. package/build/esm2022/infinite-query-options.mjs +0 -12
  33. package/build/esm2022/inject-infinite-query.mjs +0 -15
  34. package/build/esm2022/inject-is-fetching.mjs +0 -38
  35. package/build/esm2022/inject-is-mutating.mjs +0 -37
  36. package/build/esm2022/inject-mutation-state.mjs +0 -47
  37. package/build/esm2022/inject-mutation.mjs +0 -51
  38. package/build/esm2022/inject-queries.mjs +0 -33
  39. package/build/esm2022/inject-query-client.mjs +0 -23
  40. package/build/esm2022/inject-query.mjs +0 -44
  41. package/build/esm2022/providers.mjs +0 -206
  42. package/build/esm2022/query-options.mjs +0 -26
  43. package/build/esm2022/signal-proxy.mjs +0 -38
  44. package/build/esm2022/tanstack-angular-query-experimental.mjs +0 -5
  45. package/build/esm2022/types.mjs +0 -3
  46. package/build/esm2022/util/assert-injector/assert-injector.mjs +0 -21
  47. package/build/esm2022/util/create-injection-token/create-injection-token.mjs +0 -61
  48. package/build/esm2022/util/index.mjs +0 -9
  49. package/build/esm2022/util/is-dev-mode/is-dev-mode.mjs +0 -3
  50. package/build/esm2022/util/lazy-init/lazy-init.mjs +0 -31
  51. package/build/esm2022/util/lazy-signal-initializer/lazy-signal-initializer.mjs +0 -14
  52. package/build/fesm2022/tanstack-angular-query-experimental.mjs +0 -738
  53. package/build/fesm2022/tanstack-angular-query-experimental.mjs.map +0 -1
@@ -1,738 +0,0 @@
1
- import { notifyManager, InfiniteQueryObserver, MutationObserver, replaceEqualDeep, QueriesObserver, QueryObserver, onlineManager } from '@tanstack/query-core';
2
- export * from '@tanstack/query-core';
3
- import { untracked, computed, assertInInjectionContext, inject, Injector, runInInjectionContext, InjectionToken, NgZone, DestroyRef, signal, effect, makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, isDevMode, PLATFORM_ID } from '@angular/core';
4
- import { isPlatformBrowser, DOCUMENT } from '@angular/common';
5
-
6
- /* istanbul ignore file */
7
-
8
- /**
9
- * Allows to share and re-use query options in a type-safe way.
10
- *
11
- * The `queryKey` will be tagged with the type from `queryFn`.
12
- *
13
- * **Example**
14
- *
15
- * ```ts
16
- * const { queryKey } = queryOptions({
17
- * queryKey: ['key'],
18
- * queryFn: () => Promise.resolve(5),
19
- * // ^? Promise<number>
20
- * })
21
- *
22
- * const queryClient = new QueryClient()
23
- * const data = queryClient.getQueryData(queryKey)
24
- * // ^? number | undefined
25
- * ```
26
- * @param options - The query options to tag with the type from `queryFn`.
27
- * @returns The tagged query options.
28
- * @public
29
- */
30
- function queryOptions(options) {
31
- return options;
32
- }
33
-
34
- /**
35
- * Allows to share and re-use infinite query options in a type-safe way.
36
- *
37
- * The `queryKey` will be tagged with the type from `queryFn`.
38
- * @param options - The infinite query options to tag with the type from `queryFn`.
39
- * @returns The tagged infinite query options.
40
- * @public
41
- */
42
- function infiniteQueryOptions(options) {
43
- return options;
44
- }
45
-
46
- /**
47
- * Exposes fields of an object passed via an Angular `Signal` as `Computed` signals.
48
- * Functions on the object are passed through as-is.
49
- * @param inputSignal - `Signal` that must return an object.
50
- * @returns A proxy object with the same fields as the input object, but with each field wrapped in a `Computed` signal.
51
- */
52
- function signalProxy(inputSignal) {
53
- const internalState = {};
54
- return new Proxy(internalState, {
55
- get(target, prop) {
56
- // first check if we have it in our internal state and return it
57
- const computedField = target[prop];
58
- if (computedField)
59
- return computedField;
60
- // then, check if it's a function on the resultState and return it
61
- const targetField = untracked(inputSignal)[prop];
62
- if (typeof targetField === 'function')
63
- return targetField;
64
- // finally, create a computed field, store it and return it
65
- // @ts-expect-error
66
- return (target[prop] = computed(() => inputSignal()[prop]));
67
- },
68
- has(_, prop) {
69
- return !!untracked(inputSignal)[prop];
70
- },
71
- ownKeys() {
72
- return Reflect.ownKeys(untracked(inputSignal));
73
- },
74
- getOwnPropertyDescriptor() {
75
- return {
76
- enumerable: true,
77
- configurable: true,
78
- };
79
- },
80
- });
81
- }
82
-
83
- function shouldThrowError(throwError, params) {
84
- // Allow throwError function to override throwing behavior on a per-error basis
85
- if (typeof throwError === 'function') {
86
- return throwError(...params);
87
- }
88
- return !!throwError;
89
- }
90
- function noop() { }
91
-
92
- function lazyInit(initializer) {
93
- let object = null;
94
- const initializeObject = () => {
95
- if (!object) {
96
- object = untracked(() => initializer());
97
- }
98
- };
99
- queueMicrotask(() => initializeObject());
100
- return new Proxy({}, {
101
- get(_, prop, receiver) {
102
- initializeObject();
103
- return Reflect.get(object, prop, receiver);
104
- },
105
- has(_, prop) {
106
- initializeObject();
107
- return Reflect.has(object, prop);
108
- },
109
- ownKeys() {
110
- initializeObject();
111
- return Reflect.ownKeys(object);
112
- },
113
- getOwnPropertyDescriptor() {
114
- return {
115
- enumerable: true,
116
- configurable: true,
117
- };
118
- },
119
- });
120
- }
121
-
122
- /* eslint-disable cspell/spellchecker */
123
- /**
124
- * The code in this file is adapted from NG Extension Platform at https://ngxtension.netlify.app.
125
- *
126
- * Original Author: Chau Tran
127
- *
128
- * NG Extension Platform is an open-source project licensed under the MIT license.
129
- *
130
- * For more information about the original code, see
131
- * https://github.com/nartc/ngxtension-platform
132
- */
133
- /* eslint-enable */
134
- function assertInjector(fn, injector, runner) {
135
- !injector && assertInInjectionContext(fn);
136
- const assertedInjector = injector ?? inject(Injector);
137
- if (!runner)
138
- return assertedInjector;
139
- return runInInjectionContext(assertedInjector, runner);
140
- }
141
-
142
- /* eslint-disable cspell/spellchecker */
143
- /**
144
- * The code in this file is adapted from NG Extension Platform at https://ngxtension.netlify.app.
145
- *
146
- * Original Author: Chau Tran
147
- *
148
- * NG Extension Platform is an open-source project licensed under the MIT license.
149
- *
150
- * For more information about the original code, see
151
- * https://github.com/nartc/ngxtension-platform
152
- */
153
- /* eslint-enable */
154
- function createInjectFn(token) {
155
- return function ({ injector, ...injectOptions } = {}) {
156
- injector = assertInjector(this, injector);
157
- return runInInjectionContext(injector, () => inject(token, injectOptions));
158
- };
159
- }
160
- function createProvideFn(token, factory, opts = {}) {
161
- const { deps = [], multi = false, extraProviders = [] } = opts;
162
- return (value, isFunctionValue = false) => {
163
- let provider;
164
- if (value !== undefined) {
165
- // eslint-disable-next-line no-shadow
166
- const factory = typeof value === 'function'
167
- ? isFunctionValue
168
- ? () => value
169
- : value
170
- : () => value;
171
- provider = {
172
- provide: token,
173
- useFactory: factory,
174
- multi,
175
- };
176
- }
177
- else {
178
- provider = {
179
- provide: token,
180
- useFactory: factory,
181
- deps: deps,
182
- multi,
183
- };
184
- }
185
- return [extraProviders, provider];
186
- };
187
- }
188
- function createNoopInjectionToken(description, options) {
189
- const token =
190
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
191
- options?.token ||
192
- new InjectionToken(description);
193
- return [
194
- createInjectFn(token),
195
- createProvideFn(token, () => null, (options || {})),
196
- token,
197
- () => { },
198
- ];
199
- }
200
-
201
- const tokens = createNoopInjectionToken('QueryClientToken');
202
- /**
203
- * Injects the `QueryClient` instance into the component or service.
204
- *
205
- * **Example**
206
- * ```ts
207
- * const queryClient = injectQueryClient();
208
- * ```
209
- * @returns The `QueryClient` instance.
210
- * @public
211
- */
212
- const injectQueryClient = tokens[0];
213
- /**
214
- * Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the
215
- * {@link https://tanstack.com/query/latest/docs/reference/QueryClient|QueryClient}
216
- * for the entire application. You can use `provideQueryClient` to provide a
217
- * different `QueryClient` instance for a part of the application.
218
- * @public
219
- */
220
- const provideQueryClient = tokens[1];
221
- const QUERY_CLIENT = tokens[2];
222
-
223
- /**
224
- * Base implementation for `injectQuery` and `injectInfiniteQuery`.
225
- */
226
- function createBaseQuery(optionsFn, Observer) {
227
- const injector = inject(Injector);
228
- return lazyInit(() => {
229
- const ngZone = injector.get(NgZone);
230
- const destroyRef = injector.get(DestroyRef);
231
- const queryClient = injectQueryClient({ injector });
232
- /**
233
- * Signal that has the default options from query client applied
234
- * computed() is used so signals can be inserted into the options
235
- * making it reactive. Wrapping options in a function ensures embedded expressions
236
- * are preserved and can keep being applied after signal changes
237
- */
238
- const defaultedOptionsSignal = computed(() => {
239
- const options = runInInjectionContext(injector, () => optionsFn(queryClient));
240
- const defaultedOptions = queryClient.defaultQueryOptions(options);
241
- defaultedOptions._optimisticResults = 'optimistic';
242
- return defaultedOptions;
243
- });
244
- const observer = new Observer(queryClient, defaultedOptionsSignal());
245
- const resultSignal = signal(observer.getOptimisticResult(defaultedOptionsSignal()));
246
- effect(() => {
247
- const defaultedOptions = defaultedOptionsSignal();
248
- observer.setOptions(defaultedOptions, {
249
- // Do not notify on updates because of changes in the options because
250
- // these changes should already be reflected in the optimistic result.
251
- listeners: false,
252
- });
253
- untracked(() => {
254
- resultSignal.set(observer.getOptimisticResult(defaultedOptions));
255
- });
256
- }, {
257
- injector,
258
- });
259
- // observer.trackResult is not used as this optimization is not needed for Angular
260
- const unsubscribe = observer.subscribe(notifyManager.batchCalls((state) => {
261
- ngZone.run(() => {
262
- if (state.isError &&
263
- !state.isFetching &&
264
- // !isRestoring() && // todo: enable when client persistence is implemented
265
- shouldThrowError(observer.options.throwOnError, [
266
- state.error,
267
- observer.getCurrentQuery(),
268
- ])) {
269
- throw state.error;
270
- }
271
- resultSignal.set(state);
272
- });
273
- }));
274
- destroyRef.onDestroy(unsubscribe);
275
- return signalProxy(resultSignal);
276
- });
277
- }
278
-
279
- /**
280
- * Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
281
- * Infinite queries can additively "load more" data onto an existing set of data or "infinite scroll"
282
- * @param optionsFn - A function that returns infinite query options.
283
- * @param injector - The Angular injector to use.
284
- * @returns The infinite query result.
285
- * @public
286
- */
287
- function injectInfiniteQuery(optionsFn, injector) {
288
- return assertInjector(injectInfiniteQuery, injector, () => createBaseQuery(optionsFn, InfiniteQueryObserver));
289
- }
290
-
291
- /**
292
- * Injects a signal that tracks the number of queries that your application is loading or
293
- * fetching in the background.
294
- *
295
- * Can be used for app-wide loading indicators
296
- * @param filters - The filters to apply to the query.
297
- * @param injector - The Angular injector to use.
298
- * @returns signal with number of loading or fetching queries.
299
- * @public
300
- */
301
- function injectIsFetching(filters, injector) {
302
- return assertInjector(injectIsFetching, injector, () => {
303
- const queryClient = injectQueryClient();
304
- const destroyRef = inject(DestroyRef);
305
- const ngZone = inject(NgZone);
306
- const cache = queryClient.getQueryCache();
307
- // isFetching is the prev value initialized on mount *
308
- let isFetching = queryClient.isFetching(filters);
309
- const result = signal(isFetching);
310
- const unsubscribe = cache.subscribe(notifyManager.batchCalls(() => {
311
- const newIsFetching = queryClient.isFetching(filters);
312
- if (isFetching !== newIsFetching) {
313
- // * and update with each change
314
- isFetching = newIsFetching;
315
- ngZone.run(() => {
316
- result.set(isFetching);
317
- });
318
- }
319
- }));
320
- destroyRef.onDestroy(unsubscribe);
321
- return result;
322
- });
323
- }
324
-
325
- /**
326
- * Injects a signal that tracks the number of mutations that your application is fetching.
327
- *
328
- * Can be used for app-wide loading indicators
329
- * @param filters - The filters to apply to the query.
330
- * @param injector - The Angular injector to use.
331
- * @returns signal with number of fetching mutations.
332
- * @public
333
- */
334
- function injectIsMutating(filters, injector) {
335
- return assertInjector(injectIsMutating, injector, () => {
336
- const queryClient = injectQueryClient();
337
- const destroyRef = inject(DestroyRef);
338
- const ngZone = inject(NgZone);
339
- const cache = queryClient.getMutationCache();
340
- // isMutating is the prev value initialized on mount *
341
- let isMutating = queryClient.isMutating(filters);
342
- const result = signal(isMutating);
343
- const unsubscribe = cache.subscribe(notifyManager.batchCalls(() => {
344
- const newIsMutating = queryClient.isMutating(filters);
345
- if (isMutating !== newIsMutating) {
346
- // * and update with each change
347
- isMutating = newIsMutating;
348
- ngZone.run(() => {
349
- result.set(isMutating);
350
- });
351
- }
352
- }));
353
- destroyRef.onDestroy(unsubscribe);
354
- return result;
355
- });
356
- }
357
-
358
- /**
359
- * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
360
- *
361
- * Unlike queries, mutations are not run automatically.
362
- * @param optionsFn - A function that returns mutation options.
363
- * @param injector - The Angular injector to use.
364
- * @returns The mutation.
365
- * @public
366
- */
367
- function injectMutation(optionsFn, injector) {
368
- return assertInjector(injectMutation, injector, () => {
369
- const queryClient = injectQueryClient();
370
- const currentInjector = inject(Injector);
371
- const destroyRef = inject(DestroyRef);
372
- const ngZone = inject(NgZone);
373
- return lazyInit(() => runInInjectionContext(currentInjector, () => {
374
- const observer = new MutationObserver(queryClient, optionsFn(queryClient));
375
- const mutate = (variables, mutateOptions) => {
376
- observer.mutate(variables, mutateOptions).catch(noop);
377
- };
378
- effect(() => {
379
- observer.setOptions(runInInjectionContext(currentInjector, () => optionsFn(queryClient)));
380
- });
381
- const result = signal(observer.getCurrentResult());
382
- const unsubscribe = observer.subscribe(notifyManager.batchCalls((state) => {
383
- ngZone.run(() => {
384
- if (state.isError &&
385
- shouldThrowError(observer.options.throwOnError, [state.error])) {
386
- throw state.error;
387
- }
388
- result.set(state);
389
- });
390
- }));
391
- destroyRef.onDestroy(unsubscribe);
392
- const resultSignal = computed(() => ({
393
- ...result(),
394
- mutate,
395
- mutateAsync: result().mutate,
396
- }));
397
- return signalProxy(resultSignal);
398
- }));
399
- });
400
- }
401
-
402
- function lazySignalInitializer(initializerFn) {
403
- const injector = inject(Injector);
404
- let source = null;
405
- const unwrapSignal = () => {
406
- if (!source) {
407
- source = untracked(() => initializerFn(injector));
408
- }
409
- return source();
410
- };
411
- queueMicrotask(() => unwrapSignal());
412
- return computed(unwrapSignal);
413
- }
414
-
415
- function getResult(mutationCache, options) {
416
- return mutationCache
417
- .findAll(options.filters)
418
- .map((mutation) => (options.select ? options.select(mutation) : mutation.state));
419
- }
420
- /**
421
- * Injects a signal that tracks the state of all mutations.
422
- * @param mutationStateOptionsFn - A function that returns mutation state options.
423
- * @param options - The Angular injector to use.
424
- * @returns The signal that tracks the state of all mutations.
425
- * @public
426
- */
427
- function injectMutationState(mutationStateOptionsFn = () => ({}), options) {
428
- return assertInjector(injectMutationState, options?.injector, () => {
429
- const destroyRef = inject(DestroyRef);
430
- const queryClient = injectQueryClient();
431
- const ngZone = inject(NgZone);
432
- const mutationCache = queryClient.getMutationCache();
433
- return lazySignalInitializer((injector) => {
434
- const result = signal(getResult(mutationCache, mutationStateOptionsFn()));
435
- effect(() => {
436
- const mutationStateOptions = mutationStateOptionsFn();
437
- untracked(() => {
438
- // Setting the signal from an effect because it's both 'computed' from options()
439
- // and needs to be set imperatively in the mutationCache listener.
440
- result.set(getResult(mutationCache, mutationStateOptions));
441
- });
442
- }, { injector });
443
- const unsubscribe = mutationCache.subscribe(notifyManager.batchCalls(() => {
444
- const nextResult = replaceEqualDeep(result(), getResult(mutationCache, mutationStateOptionsFn()));
445
- if (result() !== nextResult) {
446
- ngZone.run(() => {
447
- result.set(nextResult);
448
- });
449
- }
450
- }));
451
- destroyRef.onDestroy(unsubscribe);
452
- return result;
453
- });
454
- });
455
- }
456
-
457
- /**
458
- * @public
459
- */
460
- function injectQueries({ queries, ...options }, injector) {
461
- return assertInjector(injectQueries, injector, () => {
462
- const queryClient = injectQueryClient();
463
- const destroyRef = inject(DestroyRef);
464
- const defaultedQueries = computed(() => {
465
- return queries().map((opts) => {
466
- const defaultedOptions = queryClient.defaultQueryOptions(opts);
467
- // Make sure the results are already in fetching state before subscribing or updating options
468
- defaultedOptions._optimisticResults = 'optimistic';
469
- return defaultedOptions;
470
- });
471
- });
472
- const observer = new QueriesObserver(queryClient, defaultedQueries(), options);
473
- // Do not notify on updates because of changes in the options because
474
- // these changes should already be reflected in the optimistic result.
475
- effect(() => {
476
- observer.setQueries(defaultedQueries(), options, { listeners: false });
477
- });
478
- const [, getCombinedResult] = observer.getOptimisticResult(defaultedQueries(), options.combine);
479
- const result = signal(getCombinedResult());
480
- const unsubscribe = observer.subscribe(notifyManager.batchCalls(result.set));
481
- destroyRef.onDestroy(unsubscribe);
482
- return result;
483
- });
484
- }
485
-
486
- /**
487
- * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
488
- *
489
- * **Basic example**
490
- * ```ts
491
- * class ServiceOrComponent {
492
- * query = injectQuery(() => ({
493
- * queryKey: ['repoData'],
494
- * queryFn: () =>
495
- * this.#http.get<Response>('https://api.github.com/repos/tanstack/query'),
496
- * }))
497
- * }
498
- * ```
499
- *
500
- * Similar to `computed` from Angular, the function passed to `injectQuery` will be run in the reactive context.
501
- * In the example below, the query will be automatically enabled and executed when the filter signal changes
502
- * to a truthy value. When the filter signal changes back to a falsy value, the query will be disabled.
503
- *
504
- * **Reactive example**
505
- * ```ts
506
- * class ServiceOrComponent {
507
- * filter = signal('')
508
- *
509
- * todosQuery = injectQuery(() => ({
510
- * queryKey: ['todos', this.filter()],
511
- * queryFn: () => fetchTodos(this.filter()),
512
- * // Signals can be combined with expressions
513
- * enabled: !!this.filter(),
514
- * }))
515
- * }
516
- * ```
517
- * @param optionsFn - A function that returns query options.
518
- * @param injector - The Angular injector to use.
519
- * @returns The query result.
520
- * @public
521
- * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
522
- */
523
- function injectQuery(optionsFn, injector) {
524
- return assertInjector(injectQuery, injector, () => createBaseQuery(optionsFn, QueryObserver));
525
- }
526
-
527
- // Re-export for mocking in tests
528
-
529
- /**
530
- * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
531
- *
532
- * Allows to configure a `QueryClient` and optional features such as developer tools.
533
- *
534
- * **Example - standalone**
535
- *
536
- * ```ts
537
- * import {
538
- * provideTanStackQuery,
539
- * QueryClient,
540
- * } from '@tanstack/angular-query-experimental'
541
- *
542
- * bootstrapApplication(AppComponent, {
543
- * providers: [provideTanStackQuery(new QueryClient())],
544
- * })
545
- * ```
546
- *
547
- * **Example - NgModule-based**
548
- *
549
- * ```ts
550
- * import {
551
- * provideTanStackQuery,
552
- * QueryClient,
553
- * } from '@tanstack/angular-query-experimental'
554
- *
555
- * @NgModule({
556
- * declarations: [AppComponent],
557
- * imports: [BrowserModule],
558
- * providers: [provideTanStackQuery(new QueryClient())],
559
- * bootstrap: [AppComponent],
560
- * })
561
- * export class AppModule {}
562
- * ```
563
- *
564
- * You can also enable optional developer tools by adding `withDevtools`. By
565
- * default the tools will then be loaded when your app is in development mode.
566
- * ```ts
567
- * import {
568
- * provideTanStackQuery,
569
- * withDevtools
570
- * QueryClient,
571
- * } from '@tanstack/angular-query-experimental'
572
- *
573
- * bootstrapApplication(AppComponent,
574
- * {
575
- * providers: [
576
- * provideTanStackQuery(new QueryClient(), withDevtools())
577
- * ]
578
- * }
579
- * )
580
- * ```
581
- * @param queryClient - A `QueryClient` instance.
582
- * @param features - Optional features to configure additional Query functionality.
583
- * @returns A set of providers to set up TanStack Query.
584
- * @public
585
- * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
586
- * @see withDevtools
587
- */
588
- function provideTanStackQuery(queryClient, ...features) {
589
- return makeEnvironmentProviders([
590
- provideQueryClient(queryClient),
591
- {
592
- provide: ENVIRONMENT_INITIALIZER,
593
- multi: true,
594
- useValue: () => {
595
- queryClient.mount();
596
- // Unmount the query client on application destroy
597
- inject(DestroyRef).onDestroy(() => queryClient.unmount());
598
- },
599
- },
600
- features.map((feature) => feature.ɵproviders),
601
- ]);
602
- }
603
- /**
604
- * Sets up providers necessary to enable TanStack Query functionality for Angular applications.
605
- *
606
- * Allows to configure a `QueryClient`.
607
- * @param queryClient - A `QueryClient` instance.
608
- * @returns A set of providers to set up TanStack Query.
609
- * @public
610
- * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
611
- * @deprecated Use `provideTanStackQuery` instead.
612
- */
613
- function provideAngularQuery(queryClient) {
614
- return provideTanStackQuery(queryClient);
615
- }
616
- /**
617
- * Helper function to create an object that represents a Query feature.
618
- * @param kind -
619
- * @param providers -
620
- * @returns A Query feature.
621
- */
622
- function queryFeature(kind, providers) {
623
- return { ɵkind: kind, ɵproviders: providers };
624
- }
625
- /**
626
- * Enables developer tools.
627
- *
628
- * **Example**
629
- *
630
- * ```ts
631
- * export const appConfig: ApplicationConfig = {
632
- * providers: [
633
- * provideTanStackQuery(new QueryClient(), withDevtools())
634
- * ]
635
- * }
636
- * ```
637
- * By default the devtools will be loaded when Angular runs in development mode and rendered in `<body>`.
638
- *
639
- * 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.
640
- *
641
- * If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
642
- * @param optionsFn - A function that returns `DevtoolsOptions`.
643
- * @returns A set of providers for use with `provideTanStackQuery`.
644
- * @public
645
- * @see {@link provideTanStackQuery}
646
- * @see {@link DevtoolsOptions}
647
- */
648
- function withDevtools(optionsFn) {
649
- let providers = [];
650
- if (!isDevMode() && !optionsFn) {
651
- providers = [];
652
- }
653
- else {
654
- providers = [
655
- {
656
- provide: ENVIRONMENT_INITIALIZER,
657
- multi: true,
658
- useFactory: () => {
659
- if (!isPlatformBrowser(inject(PLATFORM_ID)))
660
- return () => { };
661
- const injector = inject(Injector);
662
- const options = computed(() => runInInjectionContext(injector, () => optionsFn?.() ?? {}));
663
- let devtools = null;
664
- let el = null;
665
- const shouldLoadToolsSignal = computed(() => {
666
- const { loadDevtools } = options();
667
- return typeof loadDevtools === 'boolean'
668
- ? loadDevtools
669
- : isDevMode();
670
- });
671
- const doc = inject(DOCUMENT);
672
- const destroyRef = inject(DestroyRef);
673
- const getResolvedQueryClient = () => {
674
- const injectedClient = injectQueryClient({
675
- optional: true,
676
- injector,
677
- });
678
- const client = options().client ?? injectedClient;
679
- if (!client) {
680
- throw new Error('No QueryClient found');
681
- }
682
- return client;
683
- };
684
- const destroyDevtools = () => {
685
- devtools?.unmount();
686
- el?.remove();
687
- devtools = null;
688
- };
689
- return () => effect(() => {
690
- const shouldLoadTools = shouldLoadToolsSignal();
691
- const { client, position, errorTypes, buttonPosition, initialIsOpen, } = options();
692
- if (devtools && !shouldLoadTools) {
693
- destroyDevtools();
694
- return;
695
- }
696
- else if (devtools && shouldLoadTools) {
697
- client && devtools.setClient(client);
698
- position && devtools.setPosition(position);
699
- errorTypes && devtools.setErrorTypes(errorTypes);
700
- buttonPosition && devtools.setButtonPosition(buttonPosition);
701
- initialIsOpen && devtools.setInitialIsOpen(initialIsOpen);
702
- return;
703
- }
704
- else if (!shouldLoadTools) {
705
- return;
706
- }
707
- el = doc.body.appendChild(document.createElement('div'));
708
- el.classList.add('tsqd-parent-container');
709
- import('@tanstack/query-devtools').then((queryDevtools) => runInInjectionContext(injector, () => {
710
- devtools = new queryDevtools.TanstackQueryDevtools({
711
- ...options(),
712
- client: getResolvedQueryClient(),
713
- queryFlavor: 'Angular Query',
714
- version: '5',
715
- onlineManager,
716
- });
717
- el && devtools.mount(el);
718
- // Unmount the devtools on application destroy
719
- destroyRef.onDestroy(destroyDevtools);
720
- }));
721
- });
722
- },
723
- },
724
- ];
725
- }
726
- return queryFeature('DeveloperTools', providers);
727
- }
728
- const queryFeatures = ['DeveloperTools'];
729
-
730
- /* istanbul ignore file */
731
- // Re-export core
732
-
733
- /**
734
- * Generated bundle index. Do not edit.
735
- */
736
-
737
- export { QUERY_CLIENT, infiniteQueryOptions, injectInfiniteQuery, injectIsFetching, injectIsMutating, injectMutation, injectMutationState, injectQueries, injectQuery, injectQueryClient, provideAngularQuery, provideQueryClient, provideTanStackQuery, queryFeatures, queryOptions, withDevtools };
738
- //# sourceMappingURL=tanstack-angular-query-experimental.mjs.map