@tanstack/angular-query-experimental 5.103.1 → 5.103.3
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/dist/create-base-query.d.mts +169 -0
- package/dist/create-base-query.d.mts.map +1 -0
- package/dist/create-base-query.mjs +91 -0
- package/dist/create-base-query.mjs.map +1 -0
- package/dist/devtools/index.d.mts +3 -0
- package/dist/devtools/index.mjs +2 -0
- package/dist/devtools/production/index.d.mts +4 -0
- package/dist/devtools/production/index.mjs +2 -0
- package/dist/devtools/stub.d.mts +6 -0
- package/dist/devtools/stub.d.mts.map +1 -0
- package/dist/devtools/stub.mjs +9 -0
- package/dist/devtools/stub.mjs.map +1 -0
- package/dist/devtools/types.d.mts +107 -0
- package/dist/devtools/types.d.mts.map +1 -0
- package/dist/devtools/types.mjs +1 -0
- package/{devtools/with-devtools.d.ts → dist/devtools/with-devtools.d.mts} +6 -2
- package/dist/devtools/with-devtools.d.mts.map +1 -0
- package/dist/devtools/with-devtools.mjs +110 -0
- package/dist/devtools/with-devtools.mjs.map +1 -0
- package/dist/devtools-panel/index.d.mts +3 -0
- package/dist/devtools-panel/index.mjs +2 -0
- package/{devtools-panel/inject-devtools-panel.d.ts → dist/devtools-panel/inject-devtools-panel.d.mts} +6 -2
- package/dist/devtools-panel/inject-devtools-panel.d.mts.map +1 -0
- package/dist/devtools-panel/inject-devtools-panel.mjs +67 -0
- package/dist/devtools-panel/inject-devtools-panel.mjs.map +1 -0
- package/dist/devtools-panel/production/index.d.mts +4 -0
- package/dist/devtools-panel/production/index.mjs +2 -0
- package/dist/devtools-panel/stub.d.mts +6 -0
- package/dist/devtools-panel/stub.d.mts.map +1 -0
- package/dist/devtools-panel/stub.mjs +7 -0
- package/dist/devtools-panel/stub.mjs.map +1 -0
- package/dist/devtools-panel/types.d.mts +52 -0
- package/dist/devtools-panel/types.d.mts.map +1 -0
- package/dist/devtools-panel/types.mjs +1 -0
- package/dist/index.d.mts +16 -0
- package/{index.mjs → dist/index.mjs} +8 -21
- package/dist/index.mjs.map +1 -0
- package/{infinite-query-options.d.ts → dist/infinite-query-options.d.mts} +35 -31
- package/dist/infinite-query-options.d.mts.map +1 -0
- package/dist/infinite-query-options.mjs +8 -0
- package/dist/infinite-query-options.mjs.map +1 -0
- package/{inject-infinite-query.d.ts → dist/inject-infinite-query.d.mts} +18 -14
- package/dist/inject-infinite-query.d.mts.map +1 -0
- package/dist/inject-infinite-query.mjs +13 -0
- package/dist/inject-infinite-query.mjs.map +1 -0
- package/{inject-is-fetching.d.ts → dist/inject-is-fetching.d.mts} +14 -10
- package/dist/inject-is-fetching.d.mts.map +1 -0
- package/dist/inject-is-fetching.mjs +69 -0
- package/dist/inject-is-fetching.mjs.map +1 -0
- package/{inject-is-mutating.d.ts → dist/inject-is-mutating.d.mts} +14 -10
- package/dist/inject-is-mutating.d.mts.map +1 -0
- package/dist/inject-is-mutating.mjs +52 -0
- package/dist/inject-is-mutating.mjs.map +1 -0
- package/{inject-is-restoring.d.ts → dist/inject-is-restoring.d.mts} +13 -10
- package/dist/inject-is-restoring.d.mts.map +1 -0
- package/dist/inject-is-restoring.mjs +35 -0
- package/dist/inject-is-restoring.mjs.map +1 -0
- package/{inject-mutation-state.d.ts → dist/inject-mutation-state.d.mts} +16 -13
- package/dist/inject-mutation-state.d.mts.map +1 -0
- package/dist/inject-mutation-state.mjs +103 -0
- package/dist/inject-mutation-state.mjs.map +1 -0
- package/{inject-mutation.d.ts → dist/inject-mutation.d.mts} +15 -11
- package/dist/inject-mutation.d.mts.map +1 -0
- package/dist/inject-mutation.mjs +226 -0
- package/dist/inject-mutation.mjs.map +1 -0
- package/dist/inject-queries-experimental/index.d.mts +2 -0
- package/dist/inject-queries-experimental/index.mjs +2 -0
- package/{inject-queries.d.ts → dist/inject-queries.d.mts} +36 -55
- package/dist/inject-queries.d.mts.map +1 -0
- package/dist/inject-queries.mjs +203 -0
- package/dist/inject-queries.mjs.map +1 -0
- package/{inject-query-client.d.ts → dist/inject-query-client.d.mts} +8 -4
- package/dist/inject-query-client.d.mts.map +1 -0
- package/dist/inject-query-client.mjs +23 -0
- package/dist/inject-query-client.mjs.map +1 -0
- package/{inject-query.d.ts → dist/inject-query.d.mts} +18 -14
- package/dist/inject-query.d.mts.map +1 -0
- package/dist/inject-query.mjs +12 -0
- package/dist/inject-query.mjs.map +1 -0
- package/{mutation-options.d.ts → dist/mutation-options.d.mts} +8 -4
- package/dist/mutation-options.d.mts.map +1 -0
- package/dist/mutation-options.mjs +8 -0
- package/dist/mutation-options.mjs.map +1 -0
- package/dist/pending-tasks-compat.d.mts +10 -0
- package/dist/pending-tasks-compat.d.mts.map +1 -0
- package/dist/pending-tasks-compat.mjs +13 -0
- package/dist/pending-tasks-compat.mjs.map +1 -0
- package/{providers.d.ts → dist/providers.d.mts} +16 -13
- package/dist/providers.d.mts.map +1 -0
- package/dist/providers.mjs +124 -0
- package/dist/providers.mjs.map +1 -0
- package/{query-options.d.ts → dist/query-options.d.mts} +41 -37
- package/dist/query-options.d.mts.map +1 -0
- package/dist/query-options.mjs +8 -0
- package/dist/query-options.mjs.map +1 -0
- package/dist/signal-proxy.d.mts +13 -0
- package/dist/signal-proxy.d.mts.map +1 -0
- package/dist/signal-proxy.mjs +35 -0
- package/dist/signal-proxy.mjs.map +1 -0
- package/{types.d.ts → dist/types.d.mts} +36 -37
- package/dist/types.d.mts.map +1 -0
- package/dist/types.mjs +6 -0
- package/dist/types.mjs.map +1 -0
- package/package.json +48 -20
- package/src/__tests__/infinite-query-options.test-d.ts +314 -0
- package/src/__tests__/infinite-query-options.test.ts +19 -0
- package/src/__tests__/inject-devtools-panel.test.ts +196 -0
- package/src/__tests__/inject-infinite-query.test-d.ts +66 -0
- package/src/__tests__/inject-infinite-query.test.ts +227 -0
- package/src/__tests__/inject-is-fetching.test.ts +108 -0
- package/src/__tests__/inject-is-mutating.test.ts +113 -0
- package/src/__tests__/inject-is-restoring.test.ts +93 -0
- package/src/__tests__/inject-mutation-state.test-d.ts +22 -0
- package/src/__tests__/inject-mutation-state.test.ts +198 -0
- package/src/__tests__/inject-mutation.test-d.ts +158 -0
- package/src/__tests__/inject-mutation.test.ts +1161 -0
- package/src/__tests__/inject-queries.test-d.ts +196 -0
- package/src/__tests__/inject-queries.test.ts +240 -0
- package/src/__tests__/inject-query.test-d.ts +357 -0
- package/src/__tests__/inject-query.test.ts +700 -0
- package/src/__tests__/mutation-options.test-d.ts +234 -0
- package/src/__tests__/mutation-options.test.ts +344 -0
- package/src/__tests__/pending-tasks.test.ts +644 -0
- package/src/__tests__/provide-query-client.test.ts +38 -0
- package/src/__tests__/provide-tanstack-query.test.ts +38 -0
- package/src/__tests__/query-options.test-d.ts +262 -0
- package/src/__tests__/query-options.test.ts +14 -0
- package/src/__tests__/signal-proxy.test.ts +27 -0
- package/src/__tests__/test-utils.ts +77 -0
- package/src/__tests__/with-devtools.test.ts +674 -0
- package/src/create-base-query.ts +175 -0
- package/src/devtools/index.ts +8 -0
- package/src/devtools/production/index.ts +1 -0
- package/src/devtools/stub.ts +7 -0
- package/src/devtools/types.ts +116 -0
- package/src/devtools/with-devtools.ts +182 -0
- package/src/devtools-panel/index.ts +8 -0
- package/src/devtools-panel/inject-devtools-panel.ts +110 -0
- package/src/devtools-panel/production/index.ts +1 -0
- package/src/devtools-panel/stub.ts +7 -0
- package/src/devtools-panel/types.ts +57 -0
- package/src/index.ts +60 -0
- package/src/infinite-query-options.ts +354 -0
- package/src/inject-infinite-query.ts +296 -0
- package/src/inject-is-fetching.ts +97 -0
- package/src/inject-is-mutating.ts +80 -0
- package/src/inject-is-restoring.ts +53 -0
- package/src/inject-mutation-state.ts +167 -0
- package/src/inject-mutation.ts +328 -0
- package/src/inject-queries-experimental/index.ts +1 -0
- package/src/inject-queries.ts +479 -0
- package/src/inject-query-client.ts +22 -0
- package/src/inject-query.ts +208 -0
- package/src/mutation-options.ts +121 -0
- package/src/pending-tasks-compat.ts +27 -0
- package/src/providers.ts +170 -0
- package/src/query-options.ts +292 -0
- package/src/signal-proxy.ts +46 -0
- package/src/types.ts +429 -0
- package/create-base-query.d.ts +0 -164
- package/create-base-query.mjs +0 -99
- package/create-base-query.mjs.map +0 -1
- package/devtools/index.d.ts +0 -2
- package/devtools/index.mjs +0 -5
- package/devtools/index.mjs.map +0 -1
- package/devtools/production/index.d.ts +0 -1
- package/devtools/stub.d.ts +0 -2
- package/devtools/stub.mjs +0 -8
- package/devtools/stub.mjs.map +0 -1
- package/devtools/types.d.ts +0 -100
- package/devtools/with-devtools.mjs +0 -106
- package/devtools/with-devtools.mjs.map +0 -1
- package/devtools-panel/index.d.ts +0 -2
- package/devtools-panel/index.mjs +0 -5
- package/devtools-panel/index.mjs.map +0 -1
- package/devtools-panel/inject-devtools-panel.mjs +0 -72
- package/devtools-panel/inject-devtools-panel.mjs.map +0 -1
- package/devtools-panel/production/index.d.ts +0 -1
- package/devtools-panel/stub.d.ts +0 -2
- package/devtools-panel/stub.mjs +0 -8
- package/devtools-panel/stub.mjs.map +0 -1
- package/devtools-panel/types.d.ts +0 -48
- package/index.d.ts +0 -25
- package/index.mjs.map +0 -1
- package/infinite-query-options.mjs +0 -7
- package/infinite-query-options.mjs.map +0 -1
- package/inject-infinite-query.mjs +0 -18
- package/inject-infinite-query.mjs.map +0 -1
- package/inject-is-fetching.mjs +0 -31
- package/inject-is-fetching.mjs.map +0 -1
- package/inject-is-mutating.mjs +0 -31
- package/inject-is-mutating.mjs.map +0 -1
- package/inject-is-restoring.mjs +0 -21
- package/inject-is-restoring.mjs.map +0 -1
- package/inject-mutation-state.mjs +0 -51
- package/inject-mutation-state.mjs.map +0 -1
- package/inject-mutation.mjs +0 -94
- package/inject-mutation.mjs.map +0 -1
- package/inject-queries-experimental/index.d.ts +0 -1
- package/inject-queries-experimental/index.mjs +0 -5
- package/inject-queries-experimental/index.mjs.map +0 -1
- package/inject-queries.mjs +0 -82
- package/inject-queries.mjs.map +0 -1
- package/inject-query-client.mjs +0 -9
- package/inject-query-client.mjs.map +0 -1
- package/inject-query.mjs +0 -14
- package/inject-query.mjs.map +0 -1
- package/mutation-options.mjs +0 -7
- package/mutation-options.mjs.map +0 -1
- package/pending-tasks-compat.d.ts +0 -7
- package/pending-tasks-compat.mjs +0 -19
- package/pending-tasks-compat.mjs.map +0 -1
- package/providers.mjs +0 -32
- package/providers.mjs.map +0 -1
- package/query-options.mjs +0 -7
- package/query-options.mjs.map +0 -1
- package/signal-proxy.d.ts +0 -11
- package/signal-proxy.mjs +0 -29
- package/signal-proxy.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-mutation.mjs","names":[],"sources":["../src/inject-mutation.ts"],"sourcesContent":["import {\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n signal,\n untracked,\n} from '@angular/core'\nimport {\n MutationObserver,\n QueryClient,\n noop,\n notifyManager,\n shouldThrowError,\n} from '@tanstack/query-core'\nimport { signalProxy } from './signal-proxy'\nimport { PENDING_TASKS } from './pending-tasks-compat'\nimport type { PendingTaskRef } from './pending-tasks-compat'\nimport type { DefaultError, MutationObserverResult } from '@tanstack/query-core'\nimport type {\n CreateMutateFunction,\n CreateMutationOptions,\n CreateMutationResult,\n} from './types'\n\nexport interface InjectMutationOptions {\n /**\n * The `Injector` in which to create the mutation.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\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 *\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 `injectMutationFn` 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 {@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 * @param injectMutationFn - A function that returns mutation options. Similar to `computed` from Angular,\n * this function runs in the reactive context, so signals read inside it drive the mutation's options.\n * @param options - Additional configuration\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 *\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 *\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 *\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 *\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 injectMutationFn: () => CreateMutationOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n options?: InjectMutationOptions,\n): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {\n !options?.injector && assertInInjectionContext(injectMutation)\n const injector = options?.injector ?? inject(Injector)\n const ngZone = injector.get(NgZone)\n const pendingTasks = injector.get(PENDING_TASKS)\n const queryClient = injector.get(QueryClient)\n\n /**\n * computed() is used so signals can be inserted into the options\n * making it reactive. Wrapping options in a function ensures embedded expressions\n * are preserved and can keep being applied after signal changes\n */\n const optionsSignal = computed(injectMutationFn)\n\n const observerSignal = (() => {\n let instance: MutationObserver<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > | null = null\n\n return computed(() => {\n return (instance ||= new MutationObserver(queryClient, optionsSignal()))\n })\n })()\n\n const mutateFnSignal = computed<\n CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >(() => {\n const observer = observerSignal()\n return (\n ...args: Parameters<\n CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>\n >\n ) => {\n observer.mutate(args[0] as TVariables, args[1]).catch(noop)\n }\n })\n\n /**\n * Computed signal that gets result from mutation cache based on passed options\n */\n const resultFromInitialOptionsSignal = computed(() => {\n const observer = observerSignal()\n return observer.getCurrentResult()\n })\n\n /**\n * Signal that contains result set by subscriber\n */\n const resultFromSubscriberSignal = signal<MutationObserverResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > | null>(null)\n\n effect(\n () => {\n const observer = observerSignal()\n const observerOptions = optionsSignal()\n\n untracked(() => {\n observer.setOptions(observerOptions)\n })\n },\n {\n injector,\n },\n )\n\n effect(\n (onCleanup) => {\n // observer.trackResult is not used as this optimization is not needed for Angular\n const observer = observerSignal()\n let pendingTaskRef: PendingTaskRef | null = null\n\n untracked(() => {\n const unsubscribe = ngZone.runOutsideAngular(() =>\n observer.subscribe(\n notifyManager.batchCalls((state) => {\n ngZone.run(() => {\n // Track pending task when mutation is pending\n if (state.isPending && !pendingTaskRef) {\n pendingTaskRef = pendingTasks.add()\n }\n\n // Clear pending task when mutation is no longer pending\n if (!state.isPending && pendingTaskRef) {\n pendingTaskRef()\n pendingTaskRef = null\n }\n\n if (\n state.isError &&\n shouldThrowError(observer.options.throwOnError, [state.error])\n ) {\n ngZone.onError.emit(state.error)\n throw state.error\n }\n\n resultFromSubscriberSignal.set(state)\n })\n }),\n ),\n )\n onCleanup(() => {\n // Clean up any pending task on destroy\n if (pendingTaskRef) {\n pendingTaskRef()\n pendingTaskRef = null\n }\n unsubscribe()\n })\n })\n },\n {\n injector,\n },\n )\n\n const resultSignal = computed(() => {\n const resultFromSubscriber = resultFromSubscriberSignal()\n const resultFromInitialOptions = resultFromInitialOptionsSignal()\n\n const result = resultFromSubscriber ?? resultFromInitialOptions\n\n return {\n ...result,\n mutate: mutateFnSignal(),\n mutateAsync: result.mutate,\n }\n })\n\n return signalProxy(resultSignal) as CreateMutationResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6KA,SAAgB,eAMd,kBAMA,SACkE;CAClE,CAAC,SAAS,YAAY,yBAAyB,cAAc;CAC7D,MAAM,WAAW,SAAS,YAAY,OAAO,QAAQ;CACrD,MAAM,SAAS,SAAS,IAAI,MAAM;CAClC,MAAM,eAAe,SAAS,IAAI,aAAa;CAC/C,MAAM,cAAc,SAAS,IAAI,WAAW;;;;;;CAO5C,MAAM,gBAAgB,SAAS,gBAAgB;CAE/C,MAAM,wBAAwB;EAC5B,IAAI,WAKO;EAEX,OAAO,eAAe;GACpB,OAAQ,aAAa,IAAI,iBAAiB,aAAa,cAAc,CAAC;EACxE,CAAC;CACH,EAAA,CAAG;CAEH,MAAM,iBAAiB,eAEf;EACN,MAAM,WAAW,eAAe;EAChC,QACE,GAAG,SAGA;GACH,SAAS,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CAAC,MAAM,IAAI;EAC5D;CACF,CAAC;;;;CAKD,MAAM,iCAAiC,eAAe;EAEpD,OADiB,eACH,CAAC,CAAC,iBAAiB;CACnC,CAAC;;;;CAKD,MAAM,6BAA6B,OAKzB,IAAI;CAEd,aACQ;EACJ,MAAM,WAAW,eAAe;EAChC,MAAM,kBAAkB,cAAc;EAEtC,gBAAgB;GACd,SAAS,WAAW,eAAe;EACrC,CAAC;CACH,GACA,EACE,SACF,CACF;CAEA,QACG,cAAc;EAEb,MAAM,WAAW,eAAe;EAChC,IAAI,iBAAwC;EAE5C,gBAAgB;GACd,MAAM,cAAc,OAAO,wBACzB,SAAS,UACP,cAAc,YAAY,UAAU;IAClC,OAAO,UAAU;KAEf,IAAI,MAAM,aAAa,CAAC,gBACtB,iBAAiB,aAAa,IAAI;KAIpC,IAAI,CAAC,MAAM,aAAa,gBAAgB;MACtC,eAAe;MACf,iBAAiB;KACnB;KAEA,IACE,MAAM,WACN,iBAAiB,SAAS,QAAQ,cAAc,CAAC,MAAM,KAAK,CAAC,GAC7D;MACA,OAAO,QAAQ,KAAK,MAAM,KAAK;MAC/B,MAAM,MAAM;KACd;KAEA,2BAA2B,IAAI,KAAK;IACtC,CAAC;GACH,CAAC,CACH,CACF;GACA,gBAAgB;IAEd,IAAI,gBAAgB;KAClB,eAAe;KACf,iBAAiB;IACnB;IACA,YAAY;GACd,CAAC;EACH,CAAC;CACH,GACA,EACE,SACF,CACF;CAEA,MAAM,eAAe,eAAe;EAClC,MAAM,uBAAuB,2BAA2B;EACxD,MAAM,2BAA2B,+BAA+B;EAEhE,MAAM,SAAS,wBAAwB;EAEvC,OAAO;GACL,GAAG;GACH,QAAQ,eAAe;GACvB,aAAa,OAAO;EACtB;CACF,CAAC;CAED,OAAO,YAAY,YAAY;AAMjC"}
|
|
@@ -1,43 +1,44 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { CreateQueryOptions, CreateQueryResult, DefinedCreateQueryResult } from "./types.mjs";
|
|
2
|
+
import { Injector, Signal } from "@angular/core";
|
|
3
|
+
import { DefaultError, OmitKeyof, QueriesPlaceholderDataFunction, QueryFunction, QueryKey, ThrowOnError } from "@tanstack/query-core";
|
|
4
|
+
//#region src/inject-queries.d.ts
|
|
4
5
|
type QueryObserverOptionsForCreateQueries<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'placeholderData'> & {
|
|
5
|
-
|
|
6
|
+
placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>;
|
|
6
7
|
};
|
|
7
8
|
type MAXIMUM_DEPTH = 20;
|
|
8
9
|
type SkipTokenForCreateQueries = symbol;
|
|
9
10
|
type GetCreateQueryOptionsForCreateQueries<T> = T extends {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
queryFnData: infer TQueryFnData;
|
|
12
|
+
error?: infer TError;
|
|
13
|
+
data: infer TData;
|
|
13
14
|
} ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData> : T extends {
|
|
14
|
-
|
|
15
|
-
|
|
15
|
+
queryFnData: infer TQueryFnData;
|
|
16
|
+
error?: infer TError;
|
|
16
17
|
} ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError> : T extends {
|
|
17
|
-
|
|
18
|
-
|
|
18
|
+
data: infer TData;
|
|
19
|
+
error?: infer TError;
|
|
19
20
|
} ? QueryObserverOptionsForCreateQueries<unknown, TError, TData> : T extends [infer TQueryFnData, infer TError, infer TData] ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData> : T extends [infer TQueryFnData, infer TError] ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError> : T extends [infer TQueryFnData] ? QueryObserverOptionsForCreateQueries<TQueryFnData> : T extends {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
queryFn?: QueryFunction<infer TQueryFnData, infer TQueryKey> | SkipTokenForCreateQueries;
|
|
22
|
+
select?: (data: any) => infer TData;
|
|
23
|
+
throwOnError?: ThrowOnError<any, infer TError, any, any>;
|
|
23
24
|
} ? QueryObserverOptionsForCreateQueries<TQueryFnData, unknown extends TError ? DefaultError : TError, unknown extends TData ? TQueryFnData : TData, TQueryKey> : QueryObserverOptionsForCreateQueries;
|
|
24
25
|
type GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {
|
|
25
|
-
|
|
26
|
-
} ? unknown extends TInitialData ? CreateQueryResult<TData, TError> : TInitialData extends TData ? DefinedCreateQueryResult<TData, TError> : TInitialData extends () => infer TInitialDataResult ? unknown extends TInitialDataResult ? CreateQueryResult<TData, TError> : TInitialDataResult extends TData ? DefinedCreateQueryResult<TData, TError> : CreateQueryResult<TData, TError> : CreateQueryResult<TData, TError> : CreateQueryResult<TData, TError>;
|
|
26
|
+
initialData?: infer TInitialData;
|
|
27
|
+
} ? unknown extends TInitialData ? CreateQueryResult<TData, TError> : TInitialData extends TData ? DefinedCreateQueryResult<TData, TError> : TInitialData extends (() => infer TInitialDataResult) ? unknown extends TInitialDataResult ? CreateQueryResult<TData, TError> : TInitialDataResult extends TData ? DefinedCreateQueryResult<TData, TError> : CreateQueryResult<TData, TError> : CreateQueryResult<TData, TError> : CreateQueryResult<TData, TError>;
|
|
27
28
|
type GetCreateQueryResult<T> = T extends {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
29
|
+
queryFnData: any;
|
|
30
|
+
error?: infer TError;
|
|
31
|
+
data: infer TData;
|
|
31
32
|
} ? GetDefinedOrUndefinedQueryResult<T, TData, TError> : T extends {
|
|
32
|
-
|
|
33
|
-
|
|
33
|
+
queryFnData: infer TQueryFnData;
|
|
34
|
+
error?: infer TError;
|
|
34
35
|
} ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError> : T extends {
|
|
35
|
-
|
|
36
|
-
|
|
36
|
+
data: infer TData;
|
|
37
|
+
error?: infer TError;
|
|
37
38
|
} ? GetDefinedOrUndefinedQueryResult<T, TData, TError> : T extends [any, infer TError, infer TData] ? GetDefinedOrUndefinedQueryResult<T, TData, TError> : T extends [infer TQueryFnData, infer TError] ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError> : T extends [infer TQueryFnData] ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData> : T extends {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
39
|
+
queryFn?: QueryFunction<infer TQueryFnData, any> | SkipTokenForCreateQueries;
|
|
40
|
+
select?: (data: any) => infer TData;
|
|
41
|
+
throwOnError?: ThrowOnError<any, infer TError, any, any>;
|
|
41
42
|
} ? GetDefinedOrUndefinedQueryResult<T, unknown extends TData ? TQueryFnData : TData, unknown extends TError ? DefaultError : TError> : CreateQueryResult;
|
|
42
43
|
/**
|
|
43
44
|
* The `queries` array accepted by `injectQueries`. Recursively unwraps each tuple element so every entry's
|
|
@@ -52,15 +53,7 @@ type GetCreateQueryResult<T> = T extends {
|
|
|
52
53
|
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
|
|
53
54
|
* meant to be set explicitly.
|
|
54
55
|
*/
|
|
55
|
-
|
|
56
|
-
...Tails
|
|
57
|
-
], [
|
|
58
|
-
...TResults,
|
|
59
|
-
GetCreateQueryOptionsForCreateQueries<Head>
|
|
60
|
-
], [
|
|
61
|
-
...TDepth,
|
|
62
|
-
1
|
|
63
|
-
]> : 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>;
|
|
56
|
+
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<[...Tails], [...TResults, GetCreateQueryOptionsForCreateQueries<Head>], [...TDepth, 1]> : 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>;
|
|
64
57
|
/**
|
|
65
58
|
* The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:
|
|
66
59
|
* each tuple element's result type is inferred individually, up to 20 elements — past that, tuple recursion
|
|
@@ -73,24 +66,10 @@ export type QueriesOptions<T extends Array<any>, TResults extends Array<any> = [
|
|
|
73
66
|
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
|
|
74
67
|
* meant to be set explicitly.
|
|
75
68
|
*/
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
]
|
|
79
|
-
|
|
80
|
-
GetCreateQueryResult<Head>
|
|
81
|
-
], [
|
|
82
|
-
...TDepth,
|
|
83
|
-
1
|
|
84
|
-
]> : {
|
|
85
|
-
[K in keyof T]: GetCreateQueryResult<T[K]>;
|
|
86
|
-
};
|
|
87
|
-
export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = QueriesResults<T>> {
|
|
88
|
-
queries: readonly [...QueriesOptions<T>] | readonly [
|
|
89
|
-
...{
|
|
90
|
-
[K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]>;
|
|
91
|
-
}
|
|
92
|
-
];
|
|
93
|
-
combine?: (result: QueriesResults<T>) => TCombinedResult;
|
|
69
|
+
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<[...Tails], [...TResults, GetCreateQueryResult<Head>], [...TDepth, 1]> : { [K in keyof T]: GetCreateQueryResult<T[K]>; };
|
|
70
|
+
interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = QueriesResults<T>> {
|
|
71
|
+
queries: readonly [...QueriesOptions<T>] | readonly [...{ [K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]>; }];
|
|
72
|
+
combine?: (result: QueriesResults<T>) => TCombinedResult;
|
|
94
73
|
}
|
|
95
74
|
/**
|
|
96
75
|
* Injects a signal to fetch a variable number of queries.
|
|
@@ -226,5 +205,7 @@ export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = Qu
|
|
|
226
205
|
* }
|
|
227
206
|
* ```
|
|
228
207
|
*/
|
|
229
|
-
|
|
230
|
-
|
|
208
|
+
declare function injectQueries<T extends Array<any>, TCombinedResult = QueriesResults<T>>(optionsFn: () => InjectQueriesOptions<T, TCombinedResult>, injector?: Injector): Signal<TCombinedResult>;
|
|
209
|
+
//#endregion
|
|
210
|
+
export { InjectQueriesOptions, QueriesOptions, QueriesResults, injectQueries };
|
|
211
|
+
//# sourceMappingURL=inject-queries.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-queries.d.mts","names":[],"sources":["../src/inject-queries.ts"],"mappings":";;;;KAsCK,qCACH,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,YAC3B,UACF,mBAAmB,cAAc,QAAQ,OAAO;EAGhD,kBAAkB,eAAe,+BAA+B;;KAI7D;KAGA;KAEA,sCAAsC,KAEzC;EACE,mBAAmB;EACnB,cAAc;EACd,YAAY;IAEV,qCAAqC,cAAc,QAAQ,SAC3D;EAAY,mBAAmB;EAAc,cAAc;IACzD,qCAAqC,cAAc,UACnD;EAAY,YAAY;EAAO,cAAc;IAC3C,8CAA8C,QAAQ,SAEtD,iBAAiB,oBAAoB,cAAc,SACjD,qCAAqC,cAAc,QAAQ,SAC3D,iBAAiB,oBAAoB,UACnC,qCAAqC,cAAc,UACnD,iBAAiB,gBACf,qCAAqC,gBAErC;EACI,UACI,oBAAoB,oBAAoB,aACxC;EACJ,UAAU,oBAAoB;EAC9B,eAAe,wBAAwB;IAEzC,qCACE,8BACgB,SAAS,eAAe,wBACxB,QAAQ,eAAe,OACvC,aAGF;KAGb,iCAAiC,GAAG,OAAO,oBAAoB;EAClE,oBAAoB;oBAEF,eACd,kBAAkB,OAAO,UACzB,qBAAqB,QACnB,yBAAyB,OAAO,UAChC,kCAAiC,sCACf,qBACd,kBAAkB,OAAO,UACzB,2BAA2B,QACzB,yBAAyB,OAAO,UAChC,kBAAkB,OAAO,UAC7B,kBAAkB,OAAO,UAC/B,kBAAkB,OAAO;KAExB,qBAAqB,KAExB;EAAY;EAAkB,cAAc;EAAQ,YAAY;IAC5D,iCAAiC,GAAG,OAAO,UAC3C;EAAY,mBAAmB;EAAc,cAAc;IACzD,iCAAiC,GAAG,cAAc,UAClD;EAAY,YAAY;EAAO,cAAc;IAC3C,iCAAiC,GAAG,OAAO,UAE3C,sBAAsB,cAAc,SAClC,iCAAiC,GAAG,OAAO,UAC3C,iBAAiB,oBAAoB,UACnC,iCAAiC,GAAG,cAAc,UAClD,iBAAiB,gBACf,iCAAiC,GAAG,gBAEpC;EACI,UACI,oBAAoB,qBACpB;EACJ,UAAU,oBAAoB;EAC9B,eAAe,wBAAwB;IAEzC,iCACE,mBACgB,QAAQ,eAAe,uBACvB,SAAS,eAAe,UAG1C;;;;;;;;;;;;;;KAeN,eACV,UAAU,YACV,iBAAiB,iBACjB,eAAe,8BACb,yBAAyB,gBACzB,MAAM,wCACN,oBAEE,iBAAiB,YACX,UAAU,sCAAsC,SACpD,iBAAiB,eAAe,SAC9B,mBACM,YACA,UAAU,sCAAsC,YAChD,cAEN,+BAA+B,IAC7B,IAGA,UAAU,MACN,2CACQ,oBACA,cACA,aACA,cAGV,MACE,qCACE,cACA,QACA,OACA,cAIJ,MAAM;;;;;;;;;;;;;KAcR,eACV,UAAU,YACV,iBAAiB,iBACjB,eAAe,8BACb,yBAAyB,gBACzB,MAAM,qBACN,oBAEE,iBAAiB,YACX,UAAU,qBAAqB,SACnC,iBAAiB,eAAe,SAC9B,mBACM,YACA,UAAU,qBAAqB,YAC/B,iBAEH,WAAW,IAAI,qBAAqB,EAAE;UAElC,qBACf,UAAU,YACV,kBAAkB,eAAe;EAEjC,sBACiB,eAAe,sBAEpB,WAAW,IAAI,sCAAsC,EAAE;EAEnE,WAAW,QAAQ,eAAe,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAyI3B,cACd,UAAU,YACV,kBAAkB,eAAe,IAEjC,iBAAiB,qBAAqB,GAAG,kBACzC,WAAW,WACV,OAAO"}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { signalProxy } from "./signal-proxy.mjs";
|
|
2
|
+
import { injectIsRestoring } from "./inject-is-restoring.mjs";
|
|
3
|
+
import { DestroyRef, Injector, NgZone, assertInInjectionContext, computed, effect, inject, runInInjectionContext, signal, untracked } from "@angular/core";
|
|
4
|
+
import { QueriesObserver, QueryClient, notifyManager } from "@tanstack/query-core";
|
|
5
|
+
//#region src/inject-queries.ts
|
|
6
|
+
/**
|
|
7
|
+
* Injects a signal to fetch a variable number of queries.
|
|
8
|
+
*
|
|
9
|
+
* The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
|
|
10
|
+
* the same query key more than once in the array of query objects may cause some data to be shared between
|
|
11
|
+
* queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
|
|
12
|
+
* structure.
|
|
13
|
+
*
|
|
14
|
+
* The `combine` option can be used to combine the results of the queries into a single value. The result
|
|
15
|
+
* will be structurally shared to be as referentially stable as possible.
|
|
16
|
+
*
|
|
17
|
+
* @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
|
|
18
|
+
* from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
|
|
19
|
+
* the `select` parameter of a query object written inline cannot be contextually typed from that same
|
|
20
|
+
* object's `queryFn`, so it falls back to `unknown` — a
|
|
21
|
+
* [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
|
|
22
|
+
* parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
|
|
23
|
+
* object _before_ it reaches `injectQueries`, to work around this — see the example below.
|
|
24
|
+
* @param optionsFn - A function returning the queries' options — an array of query option objects under
|
|
25
|
+
* `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
|
|
26
|
+
* reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
|
|
27
|
+
* @param injector - The `Injector` in which to create the queries. If this is not provided, the current
|
|
28
|
+
* injection context will be used instead (via `inject`).
|
|
29
|
+
* @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
|
|
30
|
+
* results, in the same order as the input. When `combine` is provided, this is the value returned by
|
|
31
|
+
* `combine` instead.
|
|
32
|
+
*
|
|
33
|
+
* @example
|
|
34
|
+
* ```angular-ts
|
|
35
|
+
* @Component({
|
|
36
|
+
* selector: 'posts',
|
|
37
|
+
* template: `
|
|
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
|
+
* }
|
|
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
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* Combining results into a single value:
|
|
66
|
+
* ```angular-ts
|
|
67
|
+
* @Component({
|
|
68
|
+
* selector: 'posts',
|
|
69
|
+
* template: `
|
|
70
|
+
* @if (combined().isPending) {
|
|
71
|
+
* Loading...
|
|
72
|
+
* } @else if (combined().isError) {
|
|
73
|
+
* Error loading posts
|
|
74
|
+
* } @else {
|
|
75
|
+
* <ul>
|
|
76
|
+
* @for (post of combined().data; track post?.id) {
|
|
77
|
+
* <li>{{ post?.title }}</li>
|
|
78
|
+
* }
|
|
79
|
+
* </ul>
|
|
80
|
+
* }
|
|
81
|
+
* `,
|
|
82
|
+
* })
|
|
83
|
+
* export class Posts {
|
|
84
|
+
* readonly ids = signal([1, 2, 3])
|
|
85
|
+
*
|
|
86
|
+
* readonly combined = injectQueries(() => ({
|
|
87
|
+
* queries: this.ids().map((id) => ({
|
|
88
|
+
* queryKey: ['post', id],
|
|
89
|
+
* queryFn: () => fetchPost(id),
|
|
90
|
+
* })),
|
|
91
|
+
* combine: (postQueries) => ({
|
|
92
|
+
* data: postQueries.map((query) => query.data),
|
|
93
|
+
* isPending: postQueries.some((query) => query.isPending),
|
|
94
|
+
* isError: postQueries.some((query) => query.isError),
|
|
95
|
+
* }),
|
|
96
|
+
* }))
|
|
97
|
+
* }
|
|
98
|
+
* ```
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
|
|
102
|
+
* `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
|
|
103
|
+
* resolved before it reaches `injectQueries`:
|
|
104
|
+
* ```angular-ts
|
|
105
|
+
* const postOptions = (id: number) =>
|
|
106
|
+
* queryOptions({
|
|
107
|
+
* queryKey: ['post', id],
|
|
108
|
+
* queryFn: () => fetchPost(id),
|
|
109
|
+
* })
|
|
110
|
+
*
|
|
111
|
+
* @Component({
|
|
112
|
+
* selector: 'post-title',
|
|
113
|
+
* template: `<h1>{{ fixed()[0].data() }}</h1>`,
|
|
114
|
+
* })
|
|
115
|
+
* export class PostTitle {
|
|
116
|
+
* readonly id = signal(1)
|
|
117
|
+
*
|
|
118
|
+
* readonly broken = injectQueries(() => ({
|
|
119
|
+
* queries: [
|
|
120
|
+
* {
|
|
121
|
+
* ...postOptions(this.id()),
|
|
122
|
+
* // ❌ `data` is `unknown` here
|
|
123
|
+
* select: (data) => data.title,
|
|
124
|
+
* },
|
|
125
|
+
* ],
|
|
126
|
+
* }))
|
|
127
|
+
*
|
|
128
|
+
* readonly fixed = injectQueries(() => ({
|
|
129
|
+
* queries: [
|
|
130
|
+
* queryOptions({
|
|
131
|
+
* ...postOptions(this.id()),
|
|
132
|
+
* // ✅ `data` is `Post`
|
|
133
|
+
* select: (data) => data.title,
|
|
134
|
+
* }),
|
|
135
|
+
* ],
|
|
136
|
+
* }))
|
|
137
|
+
* }
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
function injectQueries(optionsFn, injector) {
|
|
141
|
+
!injector && assertInInjectionContext(injectQueries);
|
|
142
|
+
return runInInjectionContext(injector ?? inject(Injector), () => {
|
|
143
|
+
const destroyRef = inject(DestroyRef);
|
|
144
|
+
const ngZone = inject(NgZone);
|
|
145
|
+
const queryClient = inject(QueryClient);
|
|
146
|
+
const isRestoring = injectIsRestoring();
|
|
147
|
+
/**
|
|
148
|
+
* Signal that has the default options from query client applied
|
|
149
|
+
* computed() is used so signals can be inserted into the options
|
|
150
|
+
* making it reactive. Wrapping options in a function ensures embedded expressions
|
|
151
|
+
* are preserved and can keep being applied after signal changes
|
|
152
|
+
*/
|
|
153
|
+
const optionsSignal = computed(() => {
|
|
154
|
+
return optionsFn();
|
|
155
|
+
});
|
|
156
|
+
const defaultedQueries = computed(() => {
|
|
157
|
+
return optionsSignal().queries.map((opts) => {
|
|
158
|
+
const defaultedOptions = queryClient.defaultQueryOptions(opts);
|
|
159
|
+
defaultedOptions._optimisticResults = isRestoring() ? "isRestoring" : "optimistic";
|
|
160
|
+
return defaultedOptions;
|
|
161
|
+
});
|
|
162
|
+
});
|
|
163
|
+
const observerSignal = (() => {
|
|
164
|
+
let instance = null;
|
|
165
|
+
return computed(() => {
|
|
166
|
+
return instance ||= new QueriesObserver(queryClient, defaultedQueries(), optionsSignal());
|
|
167
|
+
});
|
|
168
|
+
})();
|
|
169
|
+
const optimisticResultSignal = computed(() => observerSignal().getOptimisticResult(defaultedQueries(), optionsSignal().combine));
|
|
170
|
+
effect(() => {
|
|
171
|
+
observerSignal().setQueries(defaultedQueries(), optionsSignal());
|
|
172
|
+
});
|
|
173
|
+
const optimisticCombinedResultSignal = computed(() => {
|
|
174
|
+
const [_optimisticResult, getCombinedResult, trackResult] = optimisticResultSignal();
|
|
175
|
+
return getCombinedResult(trackResult());
|
|
176
|
+
});
|
|
177
|
+
const resultFromSubscriberSignal = signal(null);
|
|
178
|
+
effect(() => {
|
|
179
|
+
const observer = observerSignal();
|
|
180
|
+
const [_optimisticResult, getCombinedResult] = optimisticResultSignal();
|
|
181
|
+
untracked(() => {
|
|
182
|
+
const unsubscribe = isRestoring() ? () => void 0 : ngZone.runOutsideAngular(() => observer.subscribe(notifyManager.batchCalls((state) => {
|
|
183
|
+
resultFromSubscriberSignal.set(getCombinedResult(state));
|
|
184
|
+
})));
|
|
185
|
+
destroyRef.onDestroy(unsubscribe);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
const resultSignal = computed(() => {
|
|
189
|
+
const subscriberResult = resultFromSubscriberSignal();
|
|
190
|
+
const optimisticResult = optimisticCombinedResultSignal();
|
|
191
|
+
return subscriberResult ?? optimisticResult;
|
|
192
|
+
});
|
|
193
|
+
return computed(() => {
|
|
194
|
+
const result = resultSignal();
|
|
195
|
+
const { combine } = optionsSignal();
|
|
196
|
+
return combine ? result : result.map((query) => signalProxy(signal(query)));
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
//#endregion
|
|
201
|
+
export { injectQueries };
|
|
202
|
+
|
|
203
|
+
//# sourceMappingURL=inject-queries.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-queries.mjs","names":[],"sources":["../src/inject-queries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryClient,\n notifyManager,\n} from '@tanstack/query-core'\nimport {\n DestroyRef,\n Injector,\n NgZone,\n assertInInjectionContext,\n computed,\n effect,\n inject,\n runInInjectionContext,\n signal,\n untracked,\n} from '@angular/core'\nimport { signalProxy } from './signal-proxy'\nimport { injectIsRestoring } from './inject-is-restoring'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\nimport type { Signal } from '@angular/core'\n\n// This defines the `CreateQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype QueryObserverOptionsForCreateQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForCreateQueries = symbol\n\ntype GetCreateQueryOptionsForCreateQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? QueryObserverOptionsForCreateQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? QueryObserverOptionsForCreateQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForCreateQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? QueryObserverOptionsForCreateQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n QueryObserverOptionsForCreateQueries\n\n// A defined initialData setting should return a DefinedCreateQueryResult rather than CreateQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? CreateQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedCreateQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? CreateQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedCreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n : CreateQueryResult<TData, TError>\n\ntype GetCreateQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForCreateQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n CreateQueryResult\n\n/**\n * The `queries` array accepted by `injectQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, tuple\n * recursion falls back to a single homogeneous options type. An opaque array (e.g. `unknown[]`) is returned\n * as-is; a non-tuple array of a known element type is mapped to that element type instead, with no such\n * limit.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to\n * be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<QueryObserverOptionsForCreateQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetCreateQueryOptionsForCreateQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n QueryObserverOptionsForCreateQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n QueryObserverOptionsForCreateQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<QueryObserverOptionsForCreateQueries>\n\n/**\n * The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:\n * each tuple element's result type is inferred individually, up to 20 elements — past that, tuple recursion\n * falls back to a single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped per-element\n * instead, with no such limit — every entry keeps its individually inferred type regardless of array length.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to\n * be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<CreateQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetCreateQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetCreateQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetCreateQueryResult<T[K]> }\n\nexport interface InjectQueriesOptions<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n> {\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [\n ...{ [K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]> },\n ]\n combine?: (result: QueriesResults<T>) => TCombinedResult\n}\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. The result\n * will be structurally shared to be as referentially stable as possible.\n *\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 * @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 * @param injector - The `Injector` in which to create the queries. If this is not provided, the current\n * injection context will be used instead (via `inject`).\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 *\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 *\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 *\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 injector?: Injector,\n): Signal<TCombinedResult> {\n !injector && assertInInjectionContext(injectQueries)\n return runInInjectionContext(injector ?? inject(Injector), () => {\n const destroyRef = inject(DestroyRef)\n const ngZone = inject(NgZone)\n const queryClient = inject(QueryClient)\n const isRestoring = injectIsRestoring()\n\n /**\n * Signal that has the default options from query client applied\n * computed() is used so signals can be inserted into the options\n * making it reactive. Wrapping options in a function ensures embedded expressions\n * are preserved and can keep being applied after signal changes\n */\n const optionsSignal = computed(() => {\n return optionsFn()\n })\n\n const defaultedQueries = computed(() => {\n return optionsSignal().queries.map((opts) => {\n const defaultedOptions = queryClient.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring()\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions as QueryObserverOptions\n })\n })\n\n const observerSignal = (() => {\n let instance: QueriesObserver<TCombinedResult> | null = null\n\n return computed(() => {\n return (instance ||= new QueriesObserver<TCombinedResult>(\n queryClient,\n defaultedQueries(),\n optionsSignal() as QueriesObserverOptions<TCombinedResult>,\n ))\n })\n })()\n\n const optimisticResultSignal = computed(() =>\n observerSignal().getOptimisticResult(\n defaultedQueries(),\n (optionsSignal() as QueriesObserverOptions<TCombinedResult>).combine,\n ),\n )\n\n // Do not notify on updates because of changes in the options because\n // these changes should already be reflected in the optimistic result.\n effect(() => {\n observerSignal().setQueries(\n defaultedQueries(),\n optionsSignal() as QueriesObserverOptions<TCombinedResult>,\n )\n })\n\n const optimisticCombinedResultSignal = computed(() => {\n const [_optimisticResult, getCombinedResult, trackResult] =\n optimisticResultSignal()\n return getCombinedResult(trackResult())\n })\n\n const resultFromSubscriberSignal = signal<TCombinedResult | null>(null)\n\n effect(() => {\n const observer = observerSignal()\n const [_optimisticResult, getCombinedResult] = optimisticResultSignal()\n\n untracked(() => {\n const unsubscribe = isRestoring()\n ? () => undefined\n : ngZone.runOutsideAngular(() =>\n observer.subscribe(\n notifyManager.batchCalls((state) => {\n resultFromSubscriberSignal.set(getCombinedResult(state))\n }),\n ),\n )\n\n destroyRef.onDestroy(unsubscribe)\n })\n })\n\n const resultSignal = computed(() => {\n const subscriberResult = resultFromSubscriberSignal()\n const optimisticResult = optimisticCombinedResultSignal()\n return subscriberResult ?? optimisticResult\n })\n\n return computed(() => {\n const result = resultSignal()\n const { combine } = optionsSignal()\n\n return combine\n ? result\n : (result as QueriesResults<T>).map((query) =>\n signalProxy(signal(query)),\n )\n })\n }) as unknown as Signal<TCombinedResult>\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgXA,SAAgB,cAId,WACA,UACyB;CACzB,CAAC,YAAY,yBAAyB,aAAa;CACnD,OAAO,sBAAsB,YAAY,OAAO,QAAQ,SAAS;EAC/D,MAAM,aAAa,OAAO,UAAU;EACpC,MAAM,SAAS,OAAO,MAAM;EAC5B,MAAM,cAAc,OAAO,WAAW;EACtC,MAAM,cAAc,kBAAkB;;;;;;;EAQtC,MAAM,gBAAgB,eAAe;GACnC,OAAO,UAAU;EACnB,CAAC;EAED,MAAM,mBAAmB,eAAe;GACtC,OAAO,cAAc,CAAC,CAAC,QAAQ,KAAK,SAAS;IAC3C,MAAM,mBAAmB,YAAY,oBACnC,IACF;IAEA,iBAAiB,qBAAqB,YAAY,IAC9C,gBACA;IAEJ,OAAO;GACT,CAAC;EACH,CAAC;EAED,MAAM,wBAAwB;GAC5B,IAAI,WAAoD;GAExD,OAAO,eAAe;IACpB,OAAQ,aAAa,IAAI,gBACvB,aACA,iBAAiB,GACjB,cAAc,CAChB;GACF,CAAC;EACH,EAAA,CAAG;EAEH,MAAM,yBAAyB,eAC7B,eAAe,CAAC,CAAC,oBACf,iBAAiB,GAChB,cAAc,CAAC,CAA6C,OAC/D,CACF;EAIA,aAAa;GACX,eAAe,CAAC,CAAC,WACf,iBAAiB,GACjB,cAAc,CAChB;EACF,CAAC;EAED,MAAM,iCAAiC,eAAe;GACpD,MAAM,CAAC,mBAAmB,mBAAmB,eAC3C,uBAAuB;GACzB,OAAO,kBAAkB,YAAY,CAAC;EACxC,CAAC;EAED,MAAM,6BAA6B,OAA+B,IAAI;EAEtE,aAAa;GACX,MAAM,WAAW,eAAe;GAChC,MAAM,CAAC,mBAAmB,qBAAqB,uBAAuB;GAEtE,gBAAgB;IACd,MAAM,cAAc,YAAY,UACtB,KAAA,IACN,OAAO,wBACL,SAAS,UACP,cAAc,YAAY,UAAU;KAClC,2BAA2B,IAAI,kBAAkB,KAAK,CAAC;IACzD,CAAC,CACH,CACF;IAEJ,WAAW,UAAU,WAAW;GAClC,CAAC;EACH,CAAC;EAED,MAAM,eAAe,eAAe;GAClC,MAAM,mBAAmB,2BAA2B;GACpD,MAAM,mBAAmB,+BAA+B;GACxD,OAAO,oBAAoB;EAC7B,CAAC;EAED,OAAO,eAAe;GACpB,MAAM,SAAS,aAAa;GAC5B,MAAM,EAAE,YAAY,cAAc;GAElC,OAAO,UACH,SACC,OAA6B,KAAK,UACjC,YAAY,OAAO,KAAK,CAAC,CAC3B;EACN,CAAC;CACH,CAAC;AACH"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { QueryClient } from
|
|
1
|
+
import { InjectOptions, Injector } from "@angular/core";
|
|
2
|
+
import { QueryClient } from "@tanstack/query-core";
|
|
3
|
+
//#region src/inject-query-client.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* Injects a `QueryClient` instance and allows passing a custom injector.
|
|
5
6
|
* @param injectOptions - Type of the options argument to inject and optionally a custom injector.
|
|
@@ -13,6 +14,9 @@ import { QueryClient } from '@tanstack/query-core';
|
|
|
13
14
|
* const queryClient = injectQueryClient();
|
|
14
15
|
* ```
|
|
15
16
|
*/
|
|
16
|
-
|
|
17
|
-
|
|
17
|
+
declare function injectQueryClient(injectOptions?: InjectOptions & {
|
|
18
|
+
injector?: Injector;
|
|
18
19
|
}): QueryClient;
|
|
20
|
+
//#endregion
|
|
21
|
+
export { injectQueryClient };
|
|
22
|
+
//# sourceMappingURL=inject-query-client.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-query-client.d.mts","names":[],"sources":["../src/inject-query-client.ts"],"mappings":";;;;;;;;;;;;;;;;iBAiBgB,kBACd,gBAAe;EAAkB,WAAW;IAAe"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { Injector, inject } from "@angular/core";
|
|
2
|
+
import { QueryClient } from "@tanstack/query-core";
|
|
3
|
+
//#region src/inject-query-client.ts
|
|
4
|
+
/**
|
|
5
|
+
* Injects a `QueryClient` instance and allows passing a custom injector.
|
|
6
|
+
* @param injectOptions - Type of the options argument to inject and optionally a custom injector.
|
|
7
|
+
* @returns The `QueryClient` instance.
|
|
8
|
+
* @deprecated Use `inject(QueryClient)` instead.
|
|
9
|
+
* If you need to get a `QueryClient` from a custom injector, use `injector.get(QueryClient)`.
|
|
10
|
+
*
|
|
11
|
+
*
|
|
12
|
+
* **Example**
|
|
13
|
+
* ```ts
|
|
14
|
+
* const queryClient = injectQueryClient();
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
|
+
function injectQueryClient(injectOptions = {}) {
|
|
18
|
+
return (injectOptions.injector ?? inject(Injector)).get(QueryClient);
|
|
19
|
+
}
|
|
20
|
+
//#endregion
|
|
21
|
+
export { injectQueryClient };
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=inject-query-client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-query-client.mjs","names":[],"sources":["../src/inject-query-client.ts"],"sourcesContent":["import { Injector, inject } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport type { InjectOptions } from '@angular/core'\n\n/**\n * Injects a `QueryClient` instance and allows passing a custom injector.\n * @param injectOptions - Type of the options argument to inject and optionally a custom injector.\n * @returns The `QueryClient` instance.\n * @deprecated Use `inject(QueryClient)` instead.\n * If you need to get a `QueryClient` from a custom injector, use `injector.get(QueryClient)`.\n *\n *\n * **Example**\n * ```ts\n * const queryClient = injectQueryClient();\n * ```\n */\nexport function injectQueryClient(\n injectOptions: InjectOptions & { injector?: Injector } = {},\n) {\n return (injectOptions.injector ?? inject(Injector)).get(QueryClient)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,SAAgB,kBACd,gBAAyD,CAAC,GAC1D;CACA,QAAQ,cAAc,YAAY,OAAO,QAAQ,EAAA,CAAG,IAAI,WAAW;AACrE"}
|
|
@@ -1,14 +1,15 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
1
|
+
import { CreateQueryOptions, CreateQueryResult, DefinedCreateQueryResult } from "./types.mjs";
|
|
2
|
+
import { DefinedInitialDataOptions, UndefinedInitialDataOptions } from "./query-options.mjs";
|
|
3
|
+
import { Injector } from "@angular/core";
|
|
4
|
+
import { DefaultError, QueryKey } from "@tanstack/query-core";
|
|
5
|
+
//#region src/inject-query.d.ts
|
|
6
|
+
interface InjectQueryOptions {
|
|
7
|
+
/**
|
|
8
|
+
* The `Injector` in which to create the query.
|
|
9
|
+
*
|
|
10
|
+
* If this is not provided, the current injection context will be used instead (via `inject`).
|
|
11
|
+
*/
|
|
12
|
+
injector?: Injector;
|
|
12
13
|
}
|
|
13
14
|
/**
|
|
14
15
|
* This overload is selected when `initialData` is set on the options returned by `injectQueryFn`, so the
|
|
@@ -50,7 +51,7 @@ export interface InjectQueryOptions {
|
|
|
50
51
|
* }
|
|
51
52
|
* ```
|
|
52
53
|
*/
|
|
53
|
-
|
|
54
|
+
declare function injectQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(injectQueryFn: () => DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, options?: InjectQueryOptions): DefinedCreateQueryResult<TData, TError>;
|
|
54
55
|
/**
|
|
55
56
|
* Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
|
|
56
57
|
*
|
|
@@ -125,7 +126,7 @@ export declare function injectQuery<TQueryFnData = unknown, TError = DefaultErro
|
|
|
125
126
|
* }
|
|
126
127
|
* ```
|
|
127
128
|
*/
|
|
128
|
-
|
|
129
|
+
declare function injectQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(injectQueryFn: () => UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>, options?: InjectQueryOptions): CreateQueryResult<TData, TError>;
|
|
129
130
|
/**
|
|
130
131
|
* This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware
|
|
131
132
|
* overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping
|
|
@@ -138,4 +139,7 @@ export declare function injectQuery<TQueryFnData = unknown, TError = DefaultErro
|
|
|
138
139
|
* @param options - Additional configuration
|
|
139
140
|
* @returns The query result.
|
|
140
141
|
*/
|
|
141
|
-
|
|
142
|
+
declare function injectQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(injectQueryFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>, options?: InjectQueryOptions): CreateQueryResult<TData, TError>;
|
|
143
|
+
//#endregion
|
|
144
|
+
export { InjectQueryOptions, injectQuery };
|
|
145
|
+
//# sourceMappingURL=inject-query.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-query.d.mts","names":[],"sources":["../src/inject-query.ts"],"mappings":";;;;;UAmBiB;;;;;;EAMf,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA2CG,YACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,qBAAqB,0BACnB,cACA,QACA,OACA,YAEF,UAAU,qBACT,yBAAyB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA4EnB,YACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,qBAAqB,4BACnB,cACA,QACA,OACA,YAEF,UAAU,qBACT,kBAAkB,OAAO;;;;;;;;;;;;;iBAcZ,YACd,wBACA,SAAS,cACT,QAAQ,cACR,kBAAkB,WAAW,UAE7B,qBAAqB,mBACnB,cACA,QACA,OACA,YAEF,UAAU,qBACT,kBAAkB,OAAO"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { createBaseQuery } from "./create-base-query.mjs";
|
|
2
|
+
import { Injector, assertInInjectionContext, inject, runInInjectionContext } from "@angular/core";
|
|
3
|
+
import { QueryObserver } from "@tanstack/query-core";
|
|
4
|
+
//#region src/inject-query.ts
|
|
5
|
+
function injectQuery(injectQueryFn, options) {
|
|
6
|
+
!options?.injector && assertInInjectionContext(injectQuery);
|
|
7
|
+
return runInInjectionContext(options?.injector ?? inject(Injector), () => createBaseQuery(injectQueryFn, QueryObserver));
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { injectQuery };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=inject-query.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-query.mjs","names":[],"sources":["../src/inject-query.ts"],"sourcesContent":["import { QueryObserver } from '@tanstack/query-core'\nimport {\n Injector,\n assertInInjectionContext,\n inject,\n runInInjectionContext,\n} from '@angular/core'\nimport { createBaseQuery } from './create-base-query'\nimport type { DefaultError, QueryKey } from '@tanstack/query-core'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\nimport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n} from './query-options'\n\nexport interface InjectQueryOptions {\n /**\n * The `Injector` in which to create the query.\n *\n * If this is not provided, the current injection context will be used instead (via `inject`).\n */\n injector?: Injector\n}\n\n/**\n * This overload is selected when `initialData` is set on the options returned by `injectQueryFn`, so the\n * resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.fetchQuery`.\n * @param injectQueryFn - A function returning the {@link DefinedInitialDataOptions} to use — everything you\n * can pass to `injectQuery`, with `initialData` set. Similar to `computed` from Angular, this function runs\n * in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @param options - Additional configuration\n * @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to\n * include `undefined`).\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` — even if a\n * refetch fails, so the list stays visible alongside the error. -->\n * @if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * }\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n injectQueryFn: () => DefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n options?: InjectQueryOptions,\n): DefinedCreateQueryResult<TData, TError>\n\n/**\n * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.fetchQuery`.\n * @param injectQueryFn - A function returning the {@link UndefinedInitialDataOptions} to use — everything\n * you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive\n * context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @param options - Additional configuration\n * @returns The query result. `status()` is `'pending'` if there is no cached data to display, `'error'` if\n * the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/\n * `isError` are type-guard methods for convenience.\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * }))\n * }\n * ```\n *\n * @example\n * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In\n * the example below, the query is automatically enabled and executed when the filter signal changes to a\n * truthy value. When the filter signal changes back to a falsy value, the query is disabled.\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <input [ngModel]=\"filter()\" (ngModelChange)=\"filter.set($event)\" />\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly filter = signal('')\n *\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts', this.filter()],\n * queryFn: () => fetchPosts(this.filter()),\n * // Signals can be combined with expressions\n * enabled: !!this.filter(),\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n injectQueryFn: () => UndefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n options?: InjectQueryOptions,\n): CreateQueryResult<TData, TError>\n\n/**\n * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware\n * overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping\n * `injectQuery` in your own helper function that forwards caller-provided options.\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @param injectQueryFn - A function that returns query options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive\n * the query.\n * @param options - Additional configuration\n * @returns The query result.\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n injectQueryFn: () => CreateQueryOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n options?: InjectQueryOptions,\n): CreateQueryResult<TData, TError>\n\nexport function injectQuery(\n injectQueryFn: () => CreateQueryOptions,\n options?: InjectQueryOptions,\n) {\n !options?.injector && assertInInjectionContext(injectQuery)\n return runInInjectionContext(options?.injector ?? inject(Injector), () =>\n createBaseQuery(injectQueryFn, QueryObserver),\n ) as unknown as CreateQueryResult\n}\n"],"mappings":";;;;AAuMA,SAAgB,YACd,eACA,SACA;CACA,CAAC,SAAS,YAAY,yBAAyB,WAAW;CAC1D,OAAO,sBAAsB,SAAS,YAAY,OAAO,QAAQ,SAC/D,gBAAgB,eAAe,aAAa,CAC9C;AACF"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { CreateMutationOptions } from "./types.mjs";
|
|
2
|
+
import { DefaultError, WithRequired } from "@tanstack/query-core";
|
|
3
|
+
//#region src/mutation-options.d.ts
|
|
3
4
|
/**
|
|
4
5
|
* You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. A
|
|
5
6
|
* `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
|
|
@@ -36,7 +37,7 @@ import { CreateMutationOptions } from './types.js';
|
|
|
36
37
|
* }
|
|
37
38
|
* ```
|
|
38
39
|
*/
|
|
39
|
-
|
|
40
|
+
declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: WithRequired<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): WithRequired<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
|
|
40
41
|
/**
|
|
41
42
|
* You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. No
|
|
42
43
|
* `mutationKey` is required on this overload — use this when you don't need to target the mutation via a
|
|
@@ -81,4 +82,7 @@ export declare function mutationOptions<TData = unknown, TError = DefaultError,
|
|
|
81
82
|
* }
|
|
82
83
|
* ```
|
|
83
84
|
*/
|
|
84
|
-
|
|
85
|
+
declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: Omit<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): Omit<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
|
|
86
|
+
//#endregion
|
|
87
|
+
export { mutationOptions };
|
|
88
|
+
//# sourceMappingURL=mutation-options.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mutation-options.d.mts","names":[],"sources":["../src/mutation-options.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAuCgB,gBACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,aACP,sBAAsB,OAAO,QAAQ,YAAY,mCAGlD,aACD,sBAAsB,OAAO,QAAQ,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+CnC,gBACd,iBACA,SAAS,cACT,mBACA,2BAEA,SAAS,KACP,sBAAsB,OAAO,QAAQ,YAAY,mCAGlD,KACD,sBAAsB,OAAO,QAAQ,YAAY"}
|