@tanstack/angular-query 5.0.0-rc.5 → 5.108.0
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.
- package/README.md +1 -1
- package/hydration-state-key.mjs +1 -2
- package/index.d.ts +1 -1
- package/index.mjs +1 -2
- package/index.mjs.map +1 -1
- package/infinite-query-options.d.ts +15 -13
- package/infinite-query-options.mjs +1 -2
- package/infinite-query-options.mjs.map +1 -1
- package/inject-base-query.mjs +3 -4
- package/inject-base-query.mjs.map +1 -1
- package/inject-infinite-query.d.ts +170 -33
- package/inject-infinite-query.mjs +2 -3
- package/inject-infinite-query.mjs.map +1 -1
- package/inject-is-fetching.d.ts +37 -6
- package/inject-is-fetching.mjs +36 -6
- package/inject-is-fetching.mjs.map +1 -1
- package/inject-is-mutating.d.ts +21 -6
- package/inject-is-mutating.mjs +20 -6
- package/inject-is-mutating.mjs.map +1 -1
- package/inject-is-restoring.d.ts +5 -3
- package/inject-is-restoring.mjs +6 -5
- package/inject-is-restoring.mjs.map +1 -1
- package/inject-mutation-state.d.ts +51 -3
- package/inject-mutation-state.mjs +52 -5
- package/inject-mutation-state.mjs.map +1 -1
- package/inject-mutation.d.ts +118 -13
- package/inject-mutation.mjs +121 -17
- package/inject-mutation.mjs.map +1 -1
- package/inject-queries.d.ts +113 -15
- package/inject-queries.mjs +116 -19
- package/inject-queries.mjs.map +1 -1
- package/inject-queries.types.d.ts +25 -5
- package/inject-query.d.ts +11 -8
- package/inject-query.mjs +2 -3
- package/inject-query.mjs.map +1 -1
- package/mutation-options.mjs +1 -2
- package/package.json +2 -2
- package/providers.d.ts +31 -6
- package/providers.mjs +32 -8
- package/providers.mjs.map +1 -1
- package/query-options.d.ts +23 -13
- package/query-options.mjs +1 -2
- package/query-options.mjs.map +1 -1
- package/query-resource.d.ts +4 -1
- package/query-resource.mjs +4 -2
- package/query-resource.mjs.map +1 -1
- package/schematics/migrate-from-experimental/index.js +3 -3
- package/schematics/migrate-from-experimental/workspace.js +1 -1
- package/schematics/ng-add/index.js +5 -4
- package/types.d.ts +38 -7
- package/utils/inject-external-store.mjs +1 -2
- package/utils/inject-pending-tasks-lifecycle.mjs +1 -2
- package/utils/inject-query-zone.mjs +1 -2
- package/utils/result-fields.mjs +1 -2
- package/utils/signal-proxy.mjs +1 -2
package/inject-mutation.mjs
CHANGED
|
@@ -1,35 +1,140 @@
|
|
|
1
1
|
import { injectQueryZone } from "./utils/inject-query-zone.mjs";
|
|
2
|
-
import { injectPendingTasksLifecycle } from "./utils/inject-pending-tasks-lifecycle.mjs";
|
|
3
2
|
import { injectExternalStore } from "./utils/inject-external-store.mjs";
|
|
4
|
-
import {
|
|
3
|
+
import { injectPendingTasksLifecycle } from "./utils/inject-pending-tasks-lifecycle.mjs";
|
|
5
4
|
import { mutationResultFields } from "./utils/result-fields.mjs";
|
|
5
|
+
import { signalProxy } from "./utils/signal-proxy.mjs";
|
|
6
6
|
import { MutationObserver, QueryClient, noop } from "@tanstack/query-core";
|
|
7
7
|
import { assertInInjectionContext, computed, effect, inject, untracked } from "@angular/core";
|
|
8
|
-
|
|
8
|
+
// src/inject-mutation.ts
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
11
|
-
* Unlike queries, mutations are not run automatically.
|
|
10
|
+
* Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
|
|
11
|
+
* `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
|
|
12
12
|
* @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this
|
|
13
|
-
* function runs in the reactive context, so signals read inside it drive the mutation.
|
|
14
|
-
* @returns The mutation result
|
|
13
|
+
* function runs in the reactive context, so signals read inside it drive the mutation's options.
|
|
14
|
+
* @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them
|
|
15
|
+
* (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
|
|
16
|
+
* unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
|
|
17
|
+
* `data` is defined.
|
|
18
|
+
* @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
|
|
19
|
+
* second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
|
|
20
|
+
* the shared mutation definition. Callbacks defined in `optionsFn` fire for every mutation; per-call
|
|
21
|
+
* callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,
|
|
22
|
+
* so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
|
|
15
23
|
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations
|
|
16
|
-
* @see {@link mutationOptions} to share these options
|
|
24
|
+
* @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
|
|
25
|
+
* the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
|
|
26
|
+
* @example
|
|
27
|
+
* ```angular-ts
|
|
28
|
+
* @Component({
|
|
29
|
+
* selector: 'todos',
|
|
30
|
+
* template: `
|
|
31
|
+
* @if (addMutation.isPending()) {
|
|
32
|
+
* <span>Adding todo...</span>
|
|
33
|
+
* } @else if (addMutation.isError()) {
|
|
34
|
+
* <div>An error occurred: {{ addMutation.error()?.message }}</div>
|
|
35
|
+
* }
|
|
36
|
+
* <button (click)="addMutation.mutate('Item')">Add</button>
|
|
37
|
+
* `,
|
|
38
|
+
* })
|
|
39
|
+
* export class Todos {
|
|
40
|
+
* readonly #queryClient = inject(QueryClient)
|
|
41
|
+
*
|
|
42
|
+
* readonly addMutation = injectMutation(() => ({
|
|
43
|
+
* mutationFn: addTodo,
|
|
44
|
+
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
45
|
+
* }))
|
|
46
|
+
* }
|
|
47
|
+
* ```
|
|
48
|
+
* @example
|
|
49
|
+
* Optimistic update via `onMutate`, rolling back on `onError`:
|
|
50
|
+
* ```angular-ts
|
|
51
|
+
* @Component({
|
|
52
|
+
* selector: 'todos',
|
|
53
|
+
* template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
|
|
54
|
+
* })
|
|
55
|
+
* export class Todos {
|
|
56
|
+
* readonly #queryClient = inject(QueryClient)
|
|
57
|
+
*
|
|
58
|
+
* readonly addMutation = injectMutation(() => ({
|
|
59
|
+
* mutationFn: addTodo,
|
|
60
|
+
* onMutate: async (newTodo) => {
|
|
61
|
+
* await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
|
|
62
|
+
* const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
|
|
63
|
+
*
|
|
64
|
+
* this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
|
|
65
|
+
* ...(old ?? []),
|
|
66
|
+
* newTodo,
|
|
67
|
+
* ])
|
|
68
|
+
*
|
|
69
|
+
* // Passed to `onError` as `onMutateResult` if the mutation fails.
|
|
70
|
+
* return { previousTodos }
|
|
71
|
+
* },
|
|
72
|
+
* onError: (_err, _newTodo, onMutateResult) => {
|
|
73
|
+
* this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
|
|
74
|
+
* },
|
|
75
|
+
* onSettled: () => {
|
|
76
|
+
* this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
77
|
+
* },
|
|
78
|
+
* }))
|
|
79
|
+
* }
|
|
80
|
+
* ```
|
|
17
81
|
* @example
|
|
82
|
+
* Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per
|
|
83
|
+
* call instead, so you can wait for all of them when they succeed:
|
|
18
84
|
* ```angular-ts
|
|
19
85
|
* @Component({
|
|
86
|
+
* selector: 'todos',
|
|
20
87
|
* template: `
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
88
|
+
* <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
|
|
89
|
+
* `,
|
|
90
|
+
* })
|
|
91
|
+
* export class Todos {
|
|
92
|
+
* readonly #queryClient = inject(QueryClient)
|
|
93
|
+
*
|
|
94
|
+
* readonly addMutation = injectMutation(() => ({
|
|
95
|
+
* mutationFn: addTodo,
|
|
96
|
+
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
97
|
+
* }))
|
|
98
|
+
*
|
|
99
|
+
* async handleAddAll(todos: Array<string>) {
|
|
100
|
+
* try {
|
|
101
|
+
* await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
|
|
102
|
+
* } catch (error) {
|
|
103
|
+
* console.error('Failed to add todos:', error)
|
|
25
104
|
* }
|
|
26
|
-
*
|
|
105
|
+
* }
|
|
106
|
+
* }
|
|
107
|
+
* ```
|
|
108
|
+
* @example
|
|
109
|
+
* If some of the mutations above can fail independently of the others, and you want to know which ones did —
|
|
110
|
+
* rather than losing that information the moment the first one rejects — swap `Promise.all` for
|
|
111
|
+
* `Promise.allSettled`:
|
|
112
|
+
* ```angular-ts
|
|
113
|
+
* @Component({
|
|
114
|
+
* selector: 'todos',
|
|
115
|
+
* template: `
|
|
116
|
+
* <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
|
|
27
117
|
* `,
|
|
28
118
|
* })
|
|
29
|
-
* export class
|
|
30
|
-
* readonly
|
|
31
|
-
*
|
|
119
|
+
* export class Todos {
|
|
120
|
+
* readonly #queryClient = inject(QueryClient)
|
|
121
|
+
*
|
|
122
|
+
* readonly addMutation = injectMutation(() => ({
|
|
123
|
+
* mutationFn: addTodo,
|
|
124
|
+
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
32
125
|
* }))
|
|
126
|
+
*
|
|
127
|
+
* async handleAddAll(todos: Array<string>) {
|
|
128
|
+
* const addResults = await Promise.allSettled(
|
|
129
|
+
* todos.map((todo) => this.addMutation.mutateAsync(todo)),
|
|
130
|
+
* )
|
|
131
|
+
*
|
|
132
|
+
* addResults.forEach((addResult, index) => {
|
|
133
|
+
* if (addResult.status === 'rejected') {
|
|
134
|
+
* console.error(`Failed to add "${todos[index]}":`, addResult.reason)
|
|
135
|
+
* }
|
|
136
|
+
* })
|
|
137
|
+
* }
|
|
33
138
|
* }
|
|
34
139
|
* ```
|
|
35
140
|
*/
|
|
@@ -86,7 +191,6 @@ function injectMutation(optionsFn) {
|
|
|
86
191
|
reset
|
|
87
192
|
});
|
|
88
193
|
}
|
|
89
|
-
//#endregion
|
|
90
194
|
export { injectMutation };
|
|
91
195
|
|
|
92
196
|
//# sourceMappingURL=inject-mutation.mjs.map
|
package/inject-mutation.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-mutation.mjs","names":[],"sources":["../src/inject-mutation.ts"],"sourcesContent":["import {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { MutationObserver, QueryClient, noop } from '@tanstack/query-core'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { signalProxy } from './utils/signal-proxy'\nimport { mutationResultFields } from './utils/result-fields'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport type { DefaultError } from '@tanstack/query-core'\nimport type {\n CreateMutateAsyncFunction,\n CreateMutateFunction,\n CreateMutationOptions,\n CreateMutationResult,\n} from './types'\n\n/**\n * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.\n * Unlike queries, mutations are not run automatically.\n * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it drive the mutation.\n * @returns The mutation result, including `mutate` and `mutateAsync`.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations\n * @see {@link mutationOptions} to share these options between `injectMutation` and `injectMutationState`.\n * @example\n * ```angular-ts\n * @Component({\n * template: `\n * @if (mutation.isPending()) {\n * Saving...\n * } @else if (mutation.isError()) {\n * <span>Error: {{ mutation.error()?.message }}</span>\n * }\n * <button (click)=\"mutation.mutate({ title: 'New post' })\">Create</button>\n * `,\n * })\n * export class CreatePost {\n * readonly mutation = injectMutation(() => ({\n * mutationFn: createPost,\n * }))\n * }\n * ```\n */\nexport function injectMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n optionsFn: () => CreateMutationOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectMutation)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const observerSignal = computed(\n () => new MutationObserver(queryClient, untracked(optionsSignal)),\n )\n\n // Configure the observer outside the result computation. Mutation-cache\n // listeners can synchronously read the public result while setOptions emits.\n effect(() => {\n const options = optionsSignal()\n outsideZone(() => untracked(() => observerSignal().setOptions(options)))\n })\n\n const mutationStateSignal = injectExternalStore(() => {\n const observer = observerSignal()\n return {\n getSnapshot: () => observer.getCurrentResult(),\n subscribe: (onStoreChange) => observer.subscribe(onStoreChange),\n }\n })\n\n const mutate: CreateMutateFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n mutateAsync(...args).catch(noop)\n }\n\n let pendingInvocations = 0\n\n const mutateAsync: CreateMutateAsyncFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n return outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n pendingInvocations++\n lifecycle.setPending(true)\n // Track invocations, not the observer's latest result: reset or a later\n // mutation completing must not release work which is still running.\n const settled = () => {\n pendingInvocations--\n lifecycle.setPending(pendingInvocations > 0)\n }\n try {\n return observer\n .mutate(args[0] as TVariables, args[1])\n .finally(settled)\n } catch (error) {\n settled()\n throw error\n }\n }),\n )\n }\n\n const reset = () => {\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n observer.reset()\n }),\n )\n }\n\n return Object.assign(signalProxy(mutationStateSignal, mutationResultFields), {\n mutate,\n mutateAsync,\n reset,\n }) as unknown as CreateMutationResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,eAMd,WAMkE;CAClE,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,cAAc;CAEzC,MAAM,cAAc,gBAAgB;CACpC,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,YAAY,4BAA4B;CAE9C,MAAM,gBAAgB,SAAS,SAAS;CAExC,MAAM,iBAAiB,eACf,IAAI,iBAAiB,aAAa,UAAU,aAAa,CAAC,CAClE;CAIA,aAAa;EACX,MAAM,UAAU,cAAc;EAC9B,kBAAkB,gBAAgB,eAAe,CAAC,CAAC,WAAW,OAAO,CAAC,CAAC;CACzE,CAAC;CAED,MAAM,sBAAsB,0BAA0B;EACpD,MAAM,WAAW,eAAe;EAChC,OAAO;GACL,mBAAmB,SAAS,iBAAiB;GAC7C,YAAY,kBAAkB,SAAS,UAAU,aAAa;EAChE;CACF,CAAC;CAED,MAAM,UAKD,GAAG,SAAS;EACf,YAAY,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI;CACjC;CAEA,IAAI,qBAAqB;CAEzB,MAAM,eAKD,GAAG,SAAS;EACf,OAAO,kBACL,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC;GACA,UAAU,WAAW,IAAI;GAGzB,MAAM,gBAAgB;IACpB;IACA,UAAU,WAAW,qBAAqB,CAAC;GAC7C;GACA,IAAI;IACF,OAAO,SACJ,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CACtC,QAAQ,OAAO;GACpB,SAAS,OAAO;IACd,QAAQ;IACR,MAAM;GACR;EACF,CAAC,CACH;CACF;CAEA,MAAM,cAAc;EAClB,kBACE,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC,SAAS,MAAM;EACjB,CAAC,CACH;CACF;CAEA,OAAO,OAAO,OAAO,YAAY,qBAAqB,oBAAoB,GAAG;EAC3E;EACA;EACA;CACF,CAAC;AAMH"}
|
|
1
|
+
{"version":3,"file":"inject-mutation.mjs","names":[],"sources":["../src/inject-mutation.ts"],"sourcesContent":["import {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { MutationObserver, QueryClient, noop } from '@tanstack/query-core'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { mutationResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type { DefaultError } from '@tanstack/query-core'\nimport type {\n CreateMutateAsyncFunction,\n CreateMutateFunction,\n CreateMutationOptions,\n CreateMutationResult,\n} from './types'\n\n/**\n * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.\n * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.\n * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it drive the mutation's options.\n * @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them\n * (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,\n * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether\n * `data` is defined.\n * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a\n * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to\n * the shared mutation definition. Callbacks defined in `optionsFn` fire for every mutation; per-call\n * callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,\n * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations\n * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look\n * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * @if (addMutation.isPending()) {\n * <span>Adding todo...</span>\n * } @else if (addMutation.isError()) {\n * <div>An error occurred: {{ addMutation.error()?.message }}</div>\n * }\n * <button (click)=\"addMutation.mutate('Item')\">Add</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n * }\n * ```\n * @example\n * Optimistic update via `onMutate`, rolling back on `onError`:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `<button (click)=\"addMutation.mutate('Item')\">Add</button>`,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onMutate: async (newTodo) => {\n * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })\n * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])\n *\n * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [\n * ...(old ?? []),\n * newTodo,\n * ])\n *\n * // Passed to `onError` as `onMutateResult` if the mutation fails.\n * return { previousTodos }\n * },\n * onError: (_err, _newTodo, onMutateResult) => {\n * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)\n * },\n * onSettled: () => {\n * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })\n * },\n * }))\n * }\n * ```\n * @example\n * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per\n * call instead, so you can wait for all of them when they succeed:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * <button (click)=\"handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])\">Add all</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n *\n * async handleAddAll(todos: Array<string>) {\n * try {\n * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))\n * } catch (error) {\n * console.error('Failed to add todos:', error)\n * }\n * }\n * }\n * ```\n * @example\n * If some of the mutations above can fail independently of the others, and you want to know which ones did —\n * rather than losing that information the moment the first one rejects — swap `Promise.all` for\n * `Promise.allSettled`:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * <button (click)=\"handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])\">Add all</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n *\n * async handleAddAll(todos: Array<string>) {\n * const addResults = await Promise.allSettled(\n * todos.map((todo) => this.addMutation.mutateAsync(todo)),\n * )\n *\n * addResults.forEach((addResult, index) => {\n * if (addResult.status === 'rejected') {\n * console.error(`Failed to add \"${todos[index]}\":`, addResult.reason)\n * }\n * })\n * }\n * }\n * ```\n */\nexport function injectMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n optionsFn: () => CreateMutationOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectMutation)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const observerSignal = computed(\n () => new MutationObserver(queryClient, untracked(optionsSignal)),\n )\n\n // Configure the observer outside the result computation. Mutation-cache\n // listeners can synchronously read the public result while setOptions emits.\n effect(() => {\n const options = optionsSignal()\n outsideZone(() => untracked(() => observerSignal().setOptions(options)))\n })\n\n const mutationStateSignal = injectExternalStore(() => {\n const observer = observerSignal()\n return {\n getSnapshot: () => observer.getCurrentResult(),\n subscribe: (onStoreChange) => observer.subscribe(onStoreChange),\n }\n })\n\n const mutate: CreateMutateFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n mutateAsync(...args).catch(noop)\n }\n\n let pendingInvocations = 0\n\n const mutateAsync: CreateMutateAsyncFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n return outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n pendingInvocations++\n lifecycle.setPending(true)\n // Track invocations, not the observer's latest result: reset or a later\n // mutation completing must not release work which is still running.\n const settled = () => {\n pendingInvocations--\n lifecycle.setPending(pendingInvocations > 0)\n }\n try {\n return observer\n .mutate(args[0] as TVariables, args[1])\n .finally(settled)\n } catch (error) {\n settled()\n throw error\n }\n }),\n )\n }\n\n const reset = () => {\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n observer.reset()\n }),\n )\n }\n\n return Object.assign(signalProxy(mutationStateSignal, mutationResultFields), {\n mutate,\n mutateAsync,\n reset,\n }) as unknown as CreateMutationResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyJA,SAAgB,eAMd,WAMkE;CAClE,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,cAAc;CAEzC,MAAM,cAAc,gBAAgB;CACpC,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,YAAY,4BAA4B;CAE9C,MAAM,gBAAgB,SAAS,SAAS;CAExC,MAAM,iBAAiB,eACf,IAAI,iBAAiB,aAAa,UAAU,aAAa,CAAC,CAClE;CAIA,aAAa;EACX,MAAM,UAAU,cAAc;EAC9B,kBAAkB,gBAAgB,eAAe,CAAC,CAAC,WAAW,OAAO,CAAC,CAAC;CACzE,CAAC;CAED,MAAM,sBAAsB,0BAA0B;EACpD,MAAM,WAAW,eAAe;EAChC,OAAO;GACL,mBAAmB,SAAS,iBAAiB;GAC7C,YAAY,kBAAkB,SAAS,UAAU,aAAa;EAChE;CACF,CAAC;CAED,MAAM,UAKD,GAAG,SAAS;EACf,YAAY,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI;CACjC;CAEA,IAAI,qBAAqB;CAEzB,MAAM,eAKD,GAAG,SAAS;EACf,OAAO,kBACL,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC;GACA,UAAU,WAAW,IAAI;GAGzB,MAAM,gBAAgB;IACpB;IACA,UAAU,WAAW,qBAAqB,CAAC;GAC7C;GACA,IAAI;IACF,OAAO,SACJ,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CACtC,QAAQ,OAAO;GACpB,SAAS,OAAO;IACd,QAAQ;IACR,MAAM;GACR;EACF,CAAC,CACH;CACF;CAEA,MAAM,cAAc;EAClB,kBACE,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC,SAAS,MAAM;EACjB,CAAC,CACH;CACF;CAEA,OAAO,OAAO,OAAO,YAAY,qBAAqB,oBAAoB,GAAG;EAC3E;EACA;EACA;CACF,CAAC;AAMH"}
|
package/inject-queries.d.ts
CHANGED
|
@@ -1,31 +1,129 @@
|
|
|
1
|
-
import { InjectQueriesOptions, QueriesResults } from './inject-queries.types.js';
|
|
2
1
|
import { Signal } from '@angular/core';
|
|
2
|
+
import { InjectQueriesOptions, QueriesResults } from './inject-queries.types.js';
|
|
3
3
|
/**
|
|
4
|
-
* Injects
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
4
|
+
* Injects a signal to fetch a variable number of queries.
|
|
5
|
+
*
|
|
6
|
+
* The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
|
|
7
|
+
* the same query key more than once in the array of query objects may cause some data to be shared between
|
|
8
|
+
* queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
|
|
9
|
+
* structure.
|
|
10
|
+
*
|
|
11
|
+
* The `combine` option can be used to combine the results of the queries into a single value.
|
|
12
|
+
* @param optionsFn - A function returning the queries' options — an array of query option objects under
|
|
13
|
+
* `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
|
|
14
|
+
* reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
|
|
15
|
+
* @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
|
|
16
|
+
* results, in the same order as the input. When `combine` is provided, this is the value returned by
|
|
17
|
+
* `combine` instead.
|
|
18
|
+
* @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
|
|
19
|
+
* from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
|
|
20
|
+
* the `select` parameter of a query object written inline cannot be contextually typed from that same
|
|
21
|
+
* object's `queryFn`, so it falls back to `unknown` — a
|
|
22
|
+
* [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
|
|
23
|
+
* parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
|
|
24
|
+
* object _before_ it reaches `injectQueries`, to work around this — see the example below.
|
|
8
25
|
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries
|
|
9
26
|
* @example
|
|
10
27
|
* ```angular-ts
|
|
11
28
|
* @Component({
|
|
12
|
-
* selector: '
|
|
29
|
+
* selector: 'posts',
|
|
13
30
|
* template: `
|
|
14
|
-
*
|
|
15
|
-
* @
|
|
16
|
-
*
|
|
31
|
+
* <ul>
|
|
32
|
+
* @for (query of postQueries(); track $index) {
|
|
33
|
+
* @if (query.isPending()) {
|
|
34
|
+
* <li>Loading...</li>
|
|
35
|
+
* } @else if (query.isError()) {
|
|
36
|
+
* <li>Error: {{ query.error()?.message }}</li>
|
|
37
|
+
* } @else {
|
|
38
|
+
* <li>{{ query.data().title }}</li>
|
|
39
|
+
* }
|
|
17
40
|
* }
|
|
41
|
+
* </ul>
|
|
42
|
+
* `,
|
|
43
|
+
* })
|
|
44
|
+
* export class Posts {
|
|
45
|
+
* readonly ids = signal([1, 2, 3])
|
|
46
|
+
*
|
|
47
|
+
* readonly postQueries = injectQueries(() => ({
|
|
48
|
+
* queries: this.ids().map((id) => ({
|
|
49
|
+
* queryKey: ['post', id],
|
|
50
|
+
* queryFn: () => fetchPost(id),
|
|
51
|
+
* staleTime: Infinity,
|
|
52
|
+
* })),
|
|
53
|
+
* }))
|
|
54
|
+
* }
|
|
55
|
+
* ```
|
|
56
|
+
* @example
|
|
57
|
+
* Combining results into a single value:
|
|
58
|
+
* ```angular-ts
|
|
59
|
+
* @Component({
|
|
60
|
+
* selector: 'posts',
|
|
61
|
+
* template: `
|
|
62
|
+
* @if (combined().isPending) {
|
|
63
|
+
* Loading...
|
|
64
|
+
* } @else if (combined().isError) {
|
|
65
|
+
* Error loading posts
|
|
66
|
+
* } @else {
|
|
67
|
+
* <ul>
|
|
68
|
+
* @for (post of combined().data; track post?.id) {
|
|
69
|
+
* <li>{{ post?.title }}</li>
|
|
70
|
+
* }
|
|
71
|
+
* </ul>
|
|
18
72
|
* }
|
|
19
73
|
* `,
|
|
20
74
|
* })
|
|
21
|
-
* export class
|
|
22
|
-
* readonly
|
|
75
|
+
* export class Posts {
|
|
76
|
+
* readonly ids = signal([1, 2, 3])
|
|
23
77
|
*
|
|
24
|
-
* readonly
|
|
25
|
-
* queries: this.
|
|
26
|
-
* queryKey: ['
|
|
27
|
-
* queryFn: () =>
|
|
78
|
+
* readonly combined = injectQueries(() => ({
|
|
79
|
+
* queries: this.ids().map((id) => ({
|
|
80
|
+
* queryKey: ['post', id],
|
|
81
|
+
* queryFn: () => fetchPost(id),
|
|
28
82
|
* })),
|
|
83
|
+
* combine: (postQueries) => ({
|
|
84
|
+
* data: postQueries.map((query) => query.data),
|
|
85
|
+
* isPending: postQueries.some((query) => query.isPending),
|
|
86
|
+
* isError: postQueries.some((query) => query.isError),
|
|
87
|
+
* }),
|
|
88
|
+
* }))
|
|
89
|
+
* }
|
|
90
|
+
* ```
|
|
91
|
+
* @example
|
|
92
|
+
* Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
|
|
93
|
+
* `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
|
|
94
|
+
* resolved before it reaches `injectQueries`:
|
|
95
|
+
* ```angular-ts
|
|
96
|
+
* const postOptions = (id: number) =>
|
|
97
|
+
* queryOptions({
|
|
98
|
+
* queryKey: ['post', id],
|
|
99
|
+
* queryFn: () => fetchPost(id),
|
|
100
|
+
* })
|
|
101
|
+
*
|
|
102
|
+
* @Component({
|
|
103
|
+
* selector: 'post-title',
|
|
104
|
+
* template: `<h1>{{ fixed()[0].data() }}</h1>`,
|
|
105
|
+
* })
|
|
106
|
+
* export class PostTitle {
|
|
107
|
+
* readonly id = signal(1)
|
|
108
|
+
*
|
|
109
|
+
* readonly broken = injectQueries(() => ({
|
|
110
|
+
* queries: [
|
|
111
|
+
* {
|
|
112
|
+
* ...postOptions(this.id()),
|
|
113
|
+
* // ❌ `data` is `unknown` here
|
|
114
|
+
* select: (data) => data.title,
|
|
115
|
+
* },
|
|
116
|
+
* ],
|
|
117
|
+
* }))
|
|
118
|
+
*
|
|
119
|
+
* readonly fixed = injectQueries(() => ({
|
|
120
|
+
* queries: [
|
|
121
|
+
* queryOptions({
|
|
122
|
+
* ...postOptions(this.id()),
|
|
123
|
+
* // ✅ `data` is `Post`
|
|
124
|
+
* select: (data) => data.title,
|
|
125
|
+
* }),
|
|
126
|
+
* ],
|
|
29
127
|
* }))
|
|
30
128
|
* }
|
|
31
129
|
* ```
|
package/inject-queries.mjs
CHANGED
|
@@ -1,38 +1,136 @@
|
|
|
1
|
-
import { injectQueryZone } from "./utils/inject-query-zone.mjs";
|
|
2
1
|
import { injectIsRestoring } from "./inject-is-restoring.mjs";
|
|
3
|
-
import {
|
|
2
|
+
import { injectQueryZone } from "./utils/inject-query-zone.mjs";
|
|
4
3
|
import { injectExternalStore } from "./utils/inject-external-store.mjs";
|
|
5
|
-
import {
|
|
4
|
+
import { injectPendingTasksLifecycle } from "./utils/inject-pending-tasks-lifecycle.mjs";
|
|
6
5
|
import { queryResultFields } from "./utils/result-fields.mjs";
|
|
6
|
+
import { signalProxy } from "./utils/signal-proxy.mjs";
|
|
7
7
|
import { QueriesObserver, QueryClient } from "@tanstack/query-core";
|
|
8
8
|
import { assertInInjectionContext, computed, effect, inject, untracked } from "@angular/core";
|
|
9
|
-
|
|
9
|
+
// src/inject-queries.ts
|
|
10
10
|
/**
|
|
11
|
-
* Injects
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Injects a signal to fetch a variable number of queries.
|
|
12
|
+
*
|
|
13
|
+
* The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
|
|
14
|
+
* the same query key more than once in the array of query objects may cause some data to be shared between
|
|
15
|
+
* queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
|
|
16
|
+
* structure.
|
|
17
|
+
*
|
|
18
|
+
* The `combine` option can be used to combine the results of the queries into a single value.
|
|
19
|
+
* @param optionsFn - A function returning the queries' options — an array of query option objects under
|
|
20
|
+
* `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
|
|
21
|
+
* reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
|
|
22
|
+
* @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
|
|
23
|
+
* results, in the same order as the input. When `combine` is provided, this is the value returned by
|
|
24
|
+
* `combine` instead.
|
|
25
|
+
* @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
|
|
26
|
+
* from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
|
|
27
|
+
* the `select` parameter of a query object written inline cannot be contextually typed from that same
|
|
28
|
+
* object's `queryFn`, so it falls back to `unknown` — a
|
|
29
|
+
* [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
|
|
30
|
+
* parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
|
|
31
|
+
* object _before_ it reaches `injectQueries`, to work around this — see the example below.
|
|
15
32
|
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries
|
|
16
33
|
* @example
|
|
17
34
|
* ```angular-ts
|
|
18
35
|
* @Component({
|
|
19
|
-
* selector: '
|
|
36
|
+
* selector: 'posts',
|
|
20
37
|
* template: `
|
|
21
|
-
*
|
|
22
|
-
* @
|
|
23
|
-
*
|
|
38
|
+
* <ul>
|
|
39
|
+
* @for (query of postQueries(); track $index) {
|
|
40
|
+
* @if (query.isPending()) {
|
|
41
|
+
* <li>Loading...</li>
|
|
42
|
+
* } @else if (query.isError()) {
|
|
43
|
+
* <li>Error: {{ query.error()?.message }}</li>
|
|
44
|
+
* } @else {
|
|
45
|
+
* <li>{{ query.data().title }}</li>
|
|
46
|
+
* }
|
|
24
47
|
* }
|
|
48
|
+
* </ul>
|
|
49
|
+
* `,
|
|
50
|
+
* })
|
|
51
|
+
* export class Posts {
|
|
52
|
+
* readonly ids = signal([1, 2, 3])
|
|
53
|
+
*
|
|
54
|
+
* readonly postQueries = injectQueries(() => ({
|
|
55
|
+
* queries: this.ids().map((id) => ({
|
|
56
|
+
* queryKey: ['post', id],
|
|
57
|
+
* queryFn: () => fetchPost(id),
|
|
58
|
+
* staleTime: Infinity,
|
|
59
|
+
* })),
|
|
60
|
+
* }))
|
|
61
|
+
* }
|
|
62
|
+
* ```
|
|
63
|
+
* @example
|
|
64
|
+
* Combining results into a single value:
|
|
65
|
+
* ```angular-ts
|
|
66
|
+
* @Component({
|
|
67
|
+
* selector: 'posts',
|
|
68
|
+
* template: `
|
|
69
|
+
* @if (combined().isPending) {
|
|
70
|
+
* Loading...
|
|
71
|
+
* } @else if (combined().isError) {
|
|
72
|
+
* Error loading posts
|
|
73
|
+
* } @else {
|
|
74
|
+
* <ul>
|
|
75
|
+
* @for (post of combined().data; track post?.id) {
|
|
76
|
+
* <li>{{ post?.title }}</li>
|
|
77
|
+
* }
|
|
78
|
+
* </ul>
|
|
25
79
|
* }
|
|
26
80
|
* `,
|
|
27
81
|
* })
|
|
28
|
-
* export class
|
|
29
|
-
* readonly
|
|
82
|
+
* export class Posts {
|
|
83
|
+
* readonly ids = signal([1, 2, 3])
|
|
30
84
|
*
|
|
31
|
-
* readonly
|
|
32
|
-
* queries: this.
|
|
33
|
-
* queryKey: ['
|
|
34
|
-
* queryFn: () =>
|
|
85
|
+
* readonly combined = injectQueries(() => ({
|
|
86
|
+
* queries: this.ids().map((id) => ({
|
|
87
|
+
* queryKey: ['post', id],
|
|
88
|
+
* queryFn: () => fetchPost(id),
|
|
35
89
|
* })),
|
|
90
|
+
* combine: (postQueries) => ({
|
|
91
|
+
* data: postQueries.map((query) => query.data),
|
|
92
|
+
* isPending: postQueries.some((query) => query.isPending),
|
|
93
|
+
* isError: postQueries.some((query) => query.isError),
|
|
94
|
+
* }),
|
|
95
|
+
* }))
|
|
96
|
+
* }
|
|
97
|
+
* ```
|
|
98
|
+
* @example
|
|
99
|
+
* Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
|
|
100
|
+
* `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
|
|
101
|
+
* resolved before it reaches `injectQueries`:
|
|
102
|
+
* ```angular-ts
|
|
103
|
+
* const postOptions = (id: number) =>
|
|
104
|
+
* queryOptions({
|
|
105
|
+
* queryKey: ['post', id],
|
|
106
|
+
* queryFn: () => fetchPost(id),
|
|
107
|
+
* })
|
|
108
|
+
*
|
|
109
|
+
* @Component({
|
|
110
|
+
* selector: 'post-title',
|
|
111
|
+
* template: `<h1>{{ fixed()[0].data() }}</h1>`,
|
|
112
|
+
* })
|
|
113
|
+
* export class PostTitle {
|
|
114
|
+
* readonly id = signal(1)
|
|
115
|
+
*
|
|
116
|
+
* readonly broken = injectQueries(() => ({
|
|
117
|
+
* queries: [
|
|
118
|
+
* {
|
|
119
|
+
* ...postOptions(this.id()),
|
|
120
|
+
* // ❌ `data` is `unknown` here
|
|
121
|
+
* select: (data) => data.title,
|
|
122
|
+
* },
|
|
123
|
+
* ],
|
|
124
|
+
* }))
|
|
125
|
+
*
|
|
126
|
+
* readonly fixed = injectQueries(() => ({
|
|
127
|
+
* queries: [
|
|
128
|
+
* queryOptions({
|
|
129
|
+
* ...postOptions(this.id()),
|
|
130
|
+
* // ✅ `data` is `Post`
|
|
131
|
+
* select: (data) => data.title,
|
|
132
|
+
* }),
|
|
133
|
+
* ],
|
|
36
134
|
* }))
|
|
37
135
|
* }
|
|
38
136
|
* ```
|
|
@@ -122,7 +220,6 @@ function injectQueries(optionsFn) {
|
|
|
122
220
|
return proxiedResultsSignal();
|
|
123
221
|
});
|
|
124
222
|
}
|
|
125
|
-
//#endregion
|
|
126
223
|
export { injectQueries };
|
|
127
224
|
|
|
128
225
|
//# sourceMappingURL=inject-queries.mjs.map
|
package/inject-queries.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-queries.mjs","names":[],"sources":["../src/inject-queries.ts"],"sourcesContent":["import { QueriesObserver, QueryClient } from '@tanstack/query-core'\nimport {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { signalProxy } from './utils/signal-proxy'\nimport { queryResultFields } from './utils/result-fields'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport type {\n InjectQueriesOptions,\n QueriesResults,\n} from './inject-queries.types'\nimport type {\n QueryObserverOptions,\n QueryObserverResult,\n} from '@tanstack/query-core'\nimport type { Signal } from '@angular/core'\n\n/**\n * Injects multiple queries that run in parallel and react to Angular signals.\n * @param optionsFn - A function that returns the queries' options. Similar to `computed` from Angular,\n * this function runs in the reactive context, so signals read inside it drive the queries.\n * @returns A signal containing the query results in the same order as the input queries.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'users',\n * template: `\n * @for (query of userQueries(); track $index) {\n * @if (query.isSuccess()) {\n * <p>{{ query.data().name }}</p>\n * }\n * }\n * `,\n * })\n * export class UsersComponent {\n * readonly users = input.required<Array<User>>()\n *\n * readonly userQueries = injectQueries(() => ({\n * queries: this.users().map((user) => ({\n * queryKey: ['user', user.id],\n * queryFn: () => fetchUserById(user.id),\n * })),\n * }))\n * }\n * ```\n */\nexport function injectQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,\n): Signal<TCombinedResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectQueries)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const defaultedQueries = computed(() => {\n return optionsSignal().queries.map((opts) => {\n const defaultedOptions = queryClient.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n defaultedOptions.notifyOnChangeProps = 'all'\n\n return defaultedOptions\n })\n })\n\n const shouldBlockPendingTasks = (\n observer: QueriesObserver<TCombinedResult>,\n results: Array<QueryObserverResult>,\n ) => {\n const queries = observer.getQueries()\n\n return results.some((result, index) => {\n return (\n queries[index]?.state.fetchStatus !== 'idle' ||\n (result.fetchStatus !== 'idle' && result.isEnabled)\n )\n })\n }\n\n const observerSignal = computed(\n () =>\n new QueriesObserver<TCombinedResult>(\n queryClient,\n untracked(defaultedQueries),\n ),\n )\n\n effect(() => {\n const queries = defaultedQueries()\n outsideZone(() => untracked(() => observerSignal().setQueries(queries)))\n })\n\n // Methods address the current array slot, including methods handed to combine.\n const refetches: Array<QueryObserverResult['refetch']> = []\n const getRefetch = (index: number): QueryObserverResult['refetch'] =>\n (refetches[index] ??= (options) =>\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setQueries(defaultedQueries())\n const queryObserver = observer.getObservers()[index]\n if (!queryObserver) {\n return Promise.reject(\n new Error(`Cannot refetch removed query at index ${index}`),\n )\n }\n return queryObserver.refetch(options)\n }),\n ))\n\n const resultSignal = injectExternalStore(() => {\n const observer = observerSignal()\n const restoring = isRestoring()\n return {\n getSnapshot: () => {\n const results = observer.getOptimisticResult(\n defaultedQueries(),\n undefined,\n )[0]\n refetches.length = results.length\n return results.map((result, index) => ({\n ...result,\n refetch: getRefetch(index),\n }))\n },\n subscribe: restoring\n ? undefined\n : (onStoreChange) => {\n const unsubscribe = observer.subscribe(() => {\n if (lifecycle.destroyed) return\n onStoreChange()\n })\n return () => {\n lifecycle.setPending(false)\n unsubscribe()\n }\n },\n }\n })\n\n effect((onCleanup) => {\n const results = resultSignal()\n if (isRestoring()) {\n lifecycle.setPending(false)\n return\n }\n\n lifecycle.setPending(shouldBlockPendingTasks(observerSignal(), results))\n onCleanup(() => lifecycle.setPending(false))\n })\n\n const createResultProxy = (index: number) => {\n const resultAtIndexSignal = computed(() => resultSignal()[index]!)\n return Object.assign(signalProxy(resultAtIndexSignal, queryResultFields), {\n refetch: getRefetch(index),\n })\n }\n\n const resultProxies: Array<ReturnType<typeof createResultProxy>> = []\n const proxiedResultsSignal = computed(() => {\n const results = resultSignal()\n resultProxies.length = results.length\n\n return results.map((_, index) => {\n return (resultProxies[index] ??= createResultProxy(index))\n })\n })\n\n // Combine in Angular's tracked computation. Core must notify for every raw\n // result change, including changes a previous combine function ignored.\n return computed(() => {\n const result = resultSignal()\n const { combine } = optionsSignal()\n\n if (combine)\n return combine(result as Parameters<NonNullable<typeof combine>>[0])\n\n return proxiedResultsSignal() as unknown as TCombinedResult\n })\n}\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"inject-queries.mjs","names":[],"sources":["../src/inject-queries.ts"],"sourcesContent":["import {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { QueriesObserver, QueryClient } from '@tanstack/query-core'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { queryResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type { Signal } from '@angular/core'\nimport type {\n QueryObserverOptions,\n QueryObserverResult,\n} from '@tanstack/query-core'\nimport type {\n InjectQueriesOptions,\n QueriesResults,\n} from './inject-queries.types'\n\n/**\n * Injects a signal to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having\n * the same query key more than once in the array of query objects may cause some data to be shared between\n * queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value.\n * @param optionsFn - A function returning the queries' options — an array of query option objects under\n * `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the\n * reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.\n * @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query\n * results, in the same order as the input. When `combine` is provided, this is the value returned by\n * `combine` instead.\n * @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`\n * from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,\n * the `select` parameter of a query object written inline cannot be contextually typed from that same\n * object's `queryFn`, so it falls back to `unknown` — a\n * [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`\n * parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single\n * object _before_ it reaches `injectQueries`, to work around this — see the example below.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <ul>\n * @for (query of postQueries(); track $index) {\n * @if (query.isPending()) {\n * <li>Loading...</li>\n * } @else if (query.isError()) {\n * <li>Error: {{ query.error()?.message }}</li>\n * } @else {\n * <li>{{ query.data().title }}</li>\n * }\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly ids = signal([1, 2, 3])\n *\n * readonly postQueries = injectQueries(() => ({\n * queries: this.ids().map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * }))\n * }\n * ```\n * @example\n * Combining results into a single value:\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (combined().isPending) {\n * Loading...\n * } @else if (combined().isError) {\n * Error loading posts\n * } @else {\n * <ul>\n * @for (post of combined().data; track post?.id) {\n * <li>{{ post?.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly ids = signal([1, 2, 3])\n *\n * readonly combined = injectQueries(() => ({\n * queries: this.ids().map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (postQueries) => ({\n * data: postQueries.map((query) => query.data),\n * isPending: postQueries.some((query) => query.isPending),\n * isError: postQueries.some((query) => query.isError),\n * }),\n * }))\n * }\n * ```\n * @example\n * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding\n * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is\n * resolved before it reaches `injectQueries`:\n * ```angular-ts\n * const postOptions = (id: number) =>\n * queryOptions({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })\n *\n * @Component({\n * selector: 'post-title',\n * template: `<h1>{{ fixed()[0].data() }}</h1>`,\n * })\n * export class PostTitle {\n * readonly id = signal(1)\n *\n * readonly broken = injectQueries(() => ({\n * queries: [\n * {\n * ...postOptions(this.id()),\n * // ❌ `data` is `unknown` here\n * select: (data) => data.title,\n * },\n * ],\n * }))\n *\n * readonly fixed = injectQueries(() => ({\n * queries: [\n * queryOptions({\n * ...postOptions(this.id()),\n * // ✅ `data` is `Post`\n * select: (data) => data.title,\n * }),\n * ],\n * }))\n * }\n * ```\n */\nexport function injectQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,\n): Signal<TCombinedResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectQueries)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const defaultedQueries = computed(() => {\n return optionsSignal().queries.map((opts) => {\n const defaultedOptions = queryClient.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n defaultedOptions.notifyOnChangeProps = 'all'\n\n return defaultedOptions\n })\n })\n\n const shouldBlockPendingTasks = (\n observer: QueriesObserver<TCombinedResult>,\n results: Array<QueryObserverResult>,\n ) => {\n const queries = observer.getQueries()\n\n return results.some((result, index) => {\n return (\n queries[index]?.state.fetchStatus !== 'idle' ||\n (result.fetchStatus !== 'idle' && result.isEnabled)\n )\n })\n }\n\n const observerSignal = computed(\n () =>\n new QueriesObserver<TCombinedResult>(\n queryClient,\n untracked(defaultedQueries),\n ),\n )\n\n effect(() => {\n const queries = defaultedQueries()\n outsideZone(() => untracked(() => observerSignal().setQueries(queries)))\n })\n\n // Methods address the current array slot, including methods handed to combine.\n const refetches: Array<QueryObserverResult['refetch']> = []\n const getRefetch = (index: number): QueryObserverResult['refetch'] =>\n (refetches[index] ??= (options) =>\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setQueries(defaultedQueries())\n const queryObserver = observer.getObservers()[index]\n if (!queryObserver) {\n return Promise.reject(\n new Error(`Cannot refetch removed query at index ${index}`),\n )\n }\n return queryObserver.refetch(options)\n }),\n ))\n\n const resultSignal = injectExternalStore(() => {\n const observer = observerSignal()\n const restoring = isRestoring()\n return {\n getSnapshot: () => {\n const results = observer.getOptimisticResult(\n defaultedQueries(),\n undefined,\n )[0]\n refetches.length = results.length\n return results.map((result, index) => ({\n ...result,\n refetch: getRefetch(index),\n }))\n },\n subscribe: restoring\n ? undefined\n : (onStoreChange) => {\n const unsubscribe = observer.subscribe(() => {\n if (lifecycle.destroyed) return\n onStoreChange()\n })\n return () => {\n lifecycle.setPending(false)\n unsubscribe()\n }\n },\n }\n })\n\n effect((onCleanup) => {\n const results = resultSignal()\n if (isRestoring()) {\n lifecycle.setPending(false)\n return\n }\n\n lifecycle.setPending(shouldBlockPendingTasks(observerSignal(), results))\n onCleanup(() => lifecycle.setPending(false))\n })\n\n const createResultProxy = (index: number) => {\n const resultAtIndexSignal = computed(() => resultSignal()[index]!)\n return Object.assign(signalProxy(resultAtIndexSignal, queryResultFields), {\n refetch: getRefetch(index),\n })\n }\n\n const resultProxies: Array<ReturnType<typeof createResultProxy>> = []\n const proxiedResultsSignal = computed(() => {\n const results = resultSignal()\n resultProxies.length = results.length\n\n return results.map((_, index) => {\n return (resultProxies[index] ??= createResultProxy(index))\n })\n })\n\n // Combine in Angular's tracked computation. Core must notify for every raw\n // result change, including changes a previous combine function ignored.\n return computed(() => {\n const result = resultSignal()\n const { combine } = optionsSignal()\n\n if (combine)\n return combine(result as Parameters<NonNullable<typeof combine>>[0])\n\n return proxiedResultsSignal() as unknown as TCombinedResult\n })\n}\n"],"mappings":"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"}
|
|
@@ -69,7 +69,16 @@ type InferDataAndError<T> = T extends {
|
|
|
69
69
|
type GetCreateQueryResult<T> = GenericGetDefinedOrUndefinedQueryResult<T, InferDataAndError<T>['data'], CreateQueryResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>, DefinedCreateQueryResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>>;
|
|
70
70
|
type GetQueryObserverResult<T> = GenericGetDefinedOrUndefinedQueryResult<T, InferDataAndError<T>['data'], QueryObserverResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>, DefinedQueryObserverResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>>;
|
|
71
71
|
/**
|
|
72
|
-
*
|
|
72
|
+
* The `queries` array accepted by `injectQueries`. Recursively unwraps each tuple element so every entry's
|
|
73
|
+
* `queryFn`/`select` are inferred individually, up to 20 elements — past that, tuple
|
|
74
|
+
* recursion falls back to a single homogeneous options type. An opaque array (e.g. `unknown[]`) is returned
|
|
75
|
+
* as-is; a non-tuple array of a known element type is mapped to that element type instead, with no such
|
|
76
|
+
* limit.
|
|
77
|
+
* @template T - The type of the `queries` array as written at the call site.
|
|
78
|
+
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
|
|
79
|
+
* be set explicitly.
|
|
80
|
+
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
|
|
81
|
+
* meant to be set explicitly.
|
|
73
82
|
*/
|
|
74
83
|
export type QueriesOptions<T extends Array<any>, TResults extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<QueryObserverOptionsForCreateQueries> : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>] : T extends [infer Head, ...infer Tails] ? QueriesOptions<[
|
|
75
84
|
...Tails
|
|
@@ -81,7 +90,15 @@ export type QueriesOptions<T extends Array<any>, TResults extends Array<any> = [
|
|
|
81
90
|
1
|
|
82
91
|
]> : ReadonlyArray<unknown> extends T ? T : T extends Array<QueryObserverOptionsForCreateQueries<infer TQueryFnData, infer TError, infer TData, infer TQueryKey>> ? Array<QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData, TQueryKey>> : Array<QueryObserverOptionsForCreateQueries>;
|
|
83
92
|
/**
|
|
84
|
-
*
|
|
93
|
+
* The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:
|
|
94
|
+
* each tuple element's result type is inferred individually, up to 20 elements — past that, tuple recursion
|
|
95
|
+
* falls back to a single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped per-element
|
|
96
|
+
* instead, with no such limit — every entry keeps its individually inferred type regardless of array length.
|
|
97
|
+
* @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
|
|
98
|
+
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
|
|
99
|
+
* be set explicitly.
|
|
100
|
+
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
|
|
101
|
+
* meant to be set explicitly.
|
|
85
102
|
*/
|
|
86
103
|
export type QueriesResults<T extends Array<any>, TResults extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<CreateQueryResult> : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetCreateQueryResult<Head>] : T extends [infer Head, ...infer Tails] ? QueriesResults<[
|
|
87
104
|
...Tails
|
|
@@ -106,11 +123,13 @@ type RawQueriesResults<T extends Array<any>, TResults extends Array<any> = [], T
|
|
|
106
123
|
[K in keyof T]: GetQueryObserverResult<T[K]>;
|
|
107
124
|
};
|
|
108
125
|
/**
|
|
109
|
-
*
|
|
126
|
+
* The options for `injectQueries`: the `queries` to run, and an optional `combine` function that
|
|
127
|
+
* derives a single result from all the query results.
|
|
110
128
|
*/
|
|
111
129
|
export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = QueriesResults<T>> {
|
|
112
130
|
/**
|
|
113
|
-
* The
|
|
131
|
+
* The array of query options to run, one query per element. Entries can be added, removed, or replaced
|
|
132
|
+
* reactively.
|
|
114
133
|
*/
|
|
115
134
|
queries: readonly [...QueriesOptions<T>] | readonly [
|
|
116
135
|
...{
|
|
@@ -118,7 +137,8 @@ export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = Qu
|
|
|
118
137
|
}
|
|
119
138
|
];
|
|
120
139
|
/**
|
|
121
|
-
*
|
|
140
|
+
* Combines the plain results of all the queries into a single value, which `injectQueries` returns
|
|
141
|
+
* instead of the results array. The value is recomputed reactively.
|
|
122
142
|
*/
|
|
123
143
|
combine?: (result: RawQueriesResults<T>) => TCombinedResult;
|
|
124
144
|
}
|