snapshot of https://github.com/TanStack/query.git (main, 2026-09-16; blobs > 131072B omitted)
Some checks failed
autofix.ci / autofix (push) Failing after 4s
Release / Release (push) Has been skipped
GitHub Actions Security Analysis / Run zizmor (push) Failing after 2s

This commit is contained in:
upstream-mirror
2026-09-16 01:13:08 +05:00
commit 3a013ccdfe
3570 changed files with 490194 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
{
"ignoreRules": ["cjs-resolves-to-esm"]
}

View File

@@ -0,0 +1,478 @@
# @tanstack/angular-query-experimental
## 5.102.8
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.102.8
## 5.102.7
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.102.7
## 5.102.6
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.102.6
## 5.102.5
### Patch Changes
- Updated dependencies [[`578e5c2`](https://github.com/TanStack/query/commit/578e5c26e8ebd0d7351b4b8e2bafba695e672b8d)]:
- @tanstack/query-core@5.102.5
## 5.102.4
### Patch Changes
- Updated dependencies [[`a05df6a`](https://github.com/TanStack/query/commit/a05df6aefb0e2489ec2c879ae16e2ee7cb3123ec)]:
- @tanstack/query-core@5.102.4
## 5.102.3
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.102.3
## 5.102.2
### Patch Changes
- Updated dependencies [[`80fbf73`](https://github.com/TanStack/query/commit/80fbf73e77892d702c107e14a84c219a8ed825dc)]:
- @tanstack/query-core@5.102.2
## 5.102.1
### Patch Changes
- Updated dependencies [[`134890d`](https://github.com/TanStack/query/commit/134890dbdc60e4fb0313e44b512d29284ca82f96)]:
- @tanstack/query-core@5.102.1
## 5.102.0
### Patch Changes
- [#11224](https://github.com/TanStack/query/pull/11224) [`294d4e6`](https://github.com/TanStack/query/commit/294d4e62c4f7d674574a4903eef2a1bc3dd1413b) - Fix `queryOptions` and `infiniteQueryOptions` return types so exported inferred options can be emitted in declaration files without leaking internal data tag symbols.
- [#8737](https://github.com/TanStack/query/pull/8737) [`2215bb0`](https://github.com/TanStack/query/commit/2215bb031139cdc8a84751b37a485c38ca9d2b6e) - fix: make mutation variables optional when `undefined extends TVariables`
- [#11221](https://github.com/TanStack/query/pull/11221) [`1ef4208`](https://github.com/TanStack/query/commit/1ef42087c9a266c2137d2ef645cbcc662f60ac93) - Remove experimental render-time prefetching and the `promise` property from query results.
- Updated dependencies [[`34f7cee`](https://github.com/TanStack/query/commit/34f7ceed09c10e4a3aa2df31a106ddf02ec4e787), [`b4368c4`](https://github.com/TanStack/query/commit/b4368c43792349f6c29d1fb41f7ee1ef3a8bdd2c), [`5bb089d`](https://github.com/TanStack/query/commit/5bb089d153d33933983b7ea80f8d69b51d423698), [`ba4650c`](https://github.com/TanStack/query/commit/ba4650c05e61e33c609e051b948c9f7d31ce70d1), [`294d4e6`](https://github.com/TanStack/query/commit/294d4e62c4f7d674574a4903eef2a1bc3dd1413b), [`1f631b3`](https://github.com/TanStack/query/commit/1f631b3604aab6567fb3f6c90646a5a304641546), [`01a02bf`](https://github.com/TanStack/query/commit/01a02bfad32f9efbc17796be31d6399f1197a655), [`18c1c1e`](https://github.com/TanStack/query/commit/18c1c1ef94883e781ad36d36f9ea4a043ce4260b), [`5448063`](https://github.com/TanStack/query/commit/5448063f828d2270dccd41ae375e1afde35e91f2), [`2215bb0`](https://github.com/TanStack/query/commit/2215bb031139cdc8a84751b37a485c38ca9d2b6e), [`1ef4208`](https://github.com/TanStack/query/commit/1ef42087c9a266c2137d2ef645cbcc662f60ac93), [`5981771`](https://github.com/TanStack/query/commit/5981771abec9330b344a2617543eb05ba7c99e24), [`4a9bef6`](https://github.com/TanStack/query/commit/4a9bef6cf19b1cd6b014032d696129f12a848185), [`bef4bc7`](https://github.com/TanStack/query/commit/bef4bc780ce7cca32b7e3dea85f77d92f82a62a2), [`9656dc4`](https://github.com/TanStack/query/commit/9656dc4e5fef5f8c502579b52459f9e8c72e787c), [`326aaf1`](https://github.com/TanStack/query/commit/326aaf1333e5d9cbc46569c53f218d31684162d2), [`3e83601`](https://github.com/TanStack/query/commit/3e836010032c2586e9f1c66a271fa9114a6401f9), [`c6fc17c`](https://github.com/TanStack/query/commit/c6fc17cfad6e452261c585fabfb8c210e60531ed)]:
- @tanstack/query-core@5.102.0
## 5.101.4
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.101.4
## 5.101.3
### Patch Changes
- Updated dependencies [[`7e3c822`](https://github.com/TanStack/query/commit/7e3c822a10896f41a8f1031c16b85096277af677)]:
- @tanstack/query-core@5.101.3
## 5.101.2
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.101.2
## 5.101.1
### Patch Changes
- Updated dependencies [[`9eff92e`](https://github.com/TanStack/query/commit/9eff92ed86e284ec0125b3a3539d028688235bd1)]:
- @tanstack/query-core@5.101.1
## 5.101.0
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.101.0
## 5.100.14
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.100.14
## 5.100.13
### Patch Changes
- Updated dependencies [[`d423168`](https://github.com/TanStack/query/commit/d423168f6261a5cb3d353e53b27c8150cc271151)]:
- @tanstack/query-core@5.100.13
## 5.100.12
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.100.12
## 5.100.11
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.100.11
## 5.100.10
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.100.10
## 5.100.9
### Patch Changes
- Add theme option support to Angular floating devtools. ([#10609](https://github.com/TanStack/query/pull/10609))
- Updated dependencies [[`fcee7bd`](https://github.com/TanStack/query/commit/fcee7bdc429385ae8ffa224fa8a7a9ec7b8ee380)]:
- @tanstack/query-core@5.100.9
## 5.100.8
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.100.8
## 5.100.7
### Patch Changes
- docs(devtools): align logo, panel, and 'buttonPosition' union descriptions across docs and JSDoc ([#10617](https://github.com/TanStack/query/pull/10617))
- Updated dependencies []:
- @tanstack/query-core@5.100.7
## 5.100.6
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.100.6
## 5.100.5
### Patch Changes
- Updated dependencies [[`a53ef97`](https://github.com/TanStack/query/commit/a53ef97f87decb8ea2431710f5199431d3c94c8d)]:
- @tanstack/query-core@5.100.5
## 5.100.4
### Patch Changes
- fix(devtools): change onClose callback type from () => unknown to () => void ([#10118](https://github.com/TanStack/query/pull/10118))
- Updated dependencies []:
- @tanstack/query-core@5.100.4
## 5.100.3
### Patch Changes
- Updated dependencies [[`f85d825`](https://github.com/TanStack/query/commit/f85d825e02efbbff02e2081528ed28f5e5382f7a)]:
- @tanstack/query-core@5.100.3
## 5.100.2
### Patch Changes
- Updated dependencies [[`ea4497e`](https://github.com/TanStack/query/commit/ea4497e8aa00d8c1c3a36fb1e17563a889d6ab31), [`d6a7bf3`](https://github.com/TanStack/query/commit/d6a7bf3e3e024c1a77d0536813238cc8007a5fa7), [`645d5d1`](https://github.com/TanStack/query/commit/645d5d130f5e8017cb1bf1a37987f7b980aed705)]:
- @tanstack/query-core@5.100.2
## 5.100.1
### Patch Changes
- Updated dependencies [[`1bb0d23`](https://github.com/TanStack/query/commit/1bb0d234280fd4ae1725c439088426a20593a8df)]:
- @tanstack/query-core@5.100.1
## 5.100.0
### Patch Changes
- Updated dependencies [[`6540a41`](https://github.com/TanStack/query/commit/6540a4126b1c087d86d64525e78f32d9920dcd31)]:
- @tanstack/query-core@5.100.0
## 5.99.2
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.99.2
## 5.99.1
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.99.1
## 5.99.0
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.99.0
## 5.98.0
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.98.0
## 5.97.0
### Patch Changes
- Updated dependencies [[`2bfb12c`](https://github.com/TanStack/query/commit/2bfb12cc44f1d8495106136e4ddacb817135f8f9)]:
- @tanstack/query-core@5.97.0
## 5.96.2
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.96.2
## 5.96.1
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.96.1
## 5.96.0
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.96.0
## 5.95.2
### Patch Changes
- Updated dependencies [[`cd5a35b`](https://github.com/TanStack/query/commit/cd5a35b328837781aa4f9305bb2bd7877ca934e9)]:
- @tanstack/query-core@5.95.2
## 5.95.1
### Patch Changes
- Updated dependencies [[`1f1775c`](https://github.com/TanStack/query/commit/1f1775ca92f2b6c035682947ff3b3424804ff31a)]:
- @tanstack/query-core@5.95.1
## 5.95.0
### Patch Changes
- Updated dependencies []:
- @tanstack/query-core@5.95.0
## 5.94.5
### Patch Changes
- fix(\*): resolve issue about excluded build directory ([#10312](https://github.com/TanStack/query/pull/10312))
- Updated dependencies [[`4b6536d`](https://github.com/TanStack/query/commit/4b6536dfce99036f4e37f52943c6fed3ad0e0a18)]:
- @tanstack/query-core@5.94.5
## 5.94.4
### Patch Changes
- chore: fixed version ([#10064](https://github.com/TanStack/query/pull/10064))
- Updated dependencies [[`4c75210`](https://github.com/TanStack/query/commit/4c75210ce8235fe3d39b67e1029eff11278927cc)]:
- @tanstack/query-core@5.94.4
## 5.90.28
### Patch Changes
- fix(streamedQuery): maintain error state on reset refetch with initialData defined ([#10287](https://github.com/TanStack/query/pull/10287))
- Updated dependencies [[`248975e`](https://github.com/TanStack/query/commit/248975e896f585f6eaa505c796e73fcf7bfd1eec)]:
- @tanstack/query-core@5.91.2
## 5.90.27
### Patch Changes
- Updated dependencies [[`a89aab9`](https://github.com/TanStack/query/commit/a89aab975581c25c113a26c8af486b4cafad272a)]:
- @tanstack/query-core@5.91.1
## 5.90.26
### Patch Changes
- Updated dependencies [[`6fa901b`](https://github.com/TanStack/query/commit/6fa901b97a22a80d0fca3f6ed86237ff0cbdd13b)]:
- @tanstack/query-core@5.91.0
## 5.90.25
## 5.90.24
### Patch Changes
- Updated dependencies [[`e7258c5`](https://github.com/TanStack/query/commit/e7258c5cb30cafa456cdb4e6bc75b43bf619954d)]:
- @tanstack/query-core@5.90.20
## 5.90.23
### Patch Changes
- Updated dependencies [[`53fc74e`](https://github.com/TanStack/query/commit/53fc74ebb16730bd3317f039a69c6821386bae93)]:
- @tanstack/query-core@5.90.19
## 5.90.22
### Patch Changes
- Updated dependencies [[`dea1614`](https://github.com/TanStack/query/commit/dea1614aaad5c572cf43cea54b64ac09dc4d5b41)]:
- @tanstack/query-core@5.90.18
## 5.90.21
### Patch Changes
- Updated dependencies [[`269351b`](https://github.com/TanStack/query/commit/269351b8ce4b4846da3d320ac5b850ee6aada0d6)]:
- @tanstack/query-core@5.90.17
## 5.90.20
### Patch Changes
- Updated dependencies [[`7f47906`](https://github.com/TanStack/query/commit/7f47906eaccc3f3aa5ce24b77a83bd7a620a237b)]:
- @tanstack/query-core@5.90.16
## 5.90.19
### Patch Changes
- Updated dependencies [[`fccef79`](https://github.com/TanStack/query/commit/fccef797d57d4a9566517bba87c8377f363920f2)]:
- @tanstack/query-core@5.90.15
## 5.90.18
### Patch Changes
- Updated dependencies [[`d576092`](https://github.com/TanStack/query/commit/d576092e2ece4ca3936add3eb0da5234c1d82ed4)]:
- @tanstack/query-core@5.90.14
## 5.90.17
### Patch Changes
- Updated dependencies [[`4a0a78a`](https://github.com/TanStack/query/commit/4a0a78afbc2432f8cb6828035965853fa98c86a0)]:
- @tanstack/query-core@5.90.13
## 5.90.16
### Patch Changes
- Updated dependencies [[`72d8ac5`](https://github.com/TanStack/query/commit/72d8ac5c592004b8f9c3ee086fcb9c3cd615ca05)]:
- @tanstack/query-core@5.90.12
## 5.90.15
### Patch Changes
- Updated dependencies [[`c01b150`](https://github.com/TanStack/query/commit/c01b150e3673e11d6533768529a5e6fe3ebee68c)]:
- @tanstack/query-core@5.90.11
## 5.90.14
## 5.90.13
## 5.90.12
### Patch Changes
- Updated dependencies [[`8e2e174`](https://github.com/TanStack/query/commit/8e2e174e9fd2e7b94cd232041e49c9d014d74e26), [`eb559a6`](https://github.com/TanStack/query/commit/eb559a66dc0d77dd46435f624fa64fc068bef9ae)]:
- @tanstack/query-core@5.90.10
## 5.90.11
### Patch Changes
- Updated dependencies [[`08b211f`](https://github.com/TanStack/query/commit/08b211f8aa475e05d2f13a36517fc556861ef962)]:
- @tanstack/query-core@5.90.9
## 5.90.10
### Patch Changes
- Updated dependencies [[`c0ec9fe`](https://github.com/TanStack/query/commit/c0ec9fe0d1426fe3f233adda3ebf23989ffaa110)]:
- @tanstack/query-core@5.90.8
## 5.90.9
### Patch Changes
- Updated dependencies [[`b4cd121`](https://github.com/TanStack/query/commit/b4cd121a39d07cefaa3a3411136d342cc54ce8fb)]:
- @tanstack/query-core@5.90.7
## 5.90.8
### Patch Changes
- Updated dependencies [[`1638c02`](https://github.com/TanStack/query/commit/1638c028df55648995d04431179904371a189772)]:
- @tanstack/query-core@5.90.6
## 5.90.7
### Patch Changes
- Make `injectIsMutating` signal read-only to prevent external modifications to the internal state ([#9801](https://github.com/TanStack/query/pull/9801))
## 5.90.6
### Patch Changes
- Rename `DeveloperToolsFeature` to `DevtoolsFeature` for consistency with internal naming conventions and ecosystem ([#9794](https://github.com/TanStack/query/pull/9794))
## 5.90.5
### Patch Changes
- Updated dependencies [[`e42ddfe`](https://github.com/TanStack/query/commit/e42ddfe919f34f847ca101aeef162c69845f9a1e)]:
- @tanstack/query-core@5.90.5
## 5.90.4
### Patch Changes
- Updated dependencies [[`20ef922`](https://github.com/TanStack/query/commit/20ef922a0a7c3aee00150bf69123c338b0922922)]:
- @tanstack/query-core@5.90.4
## 5.90.3
### Patch Changes
- Updated dependencies [[`4e1c433`](https://github.com/TanStack/query/commit/4e1c4338a72f7384600bbda99e44bc1891695df4)]:
- @tanstack/query-core@5.90.3

View File

@@ -0,0 +1,149 @@
<picture>
<source
media="(prefers-color-scheme: dark)"
srcset="https://tanstack.com/api/readme/query.png?framework=angular&theme=dark"
/>
<source
media="(prefers-color-scheme: light)"
srcset="https://tanstack.com/api/readme/query.png?framework=angular"
/>
<img
src="https://tanstack.com/api/readme/query.png?framework=angular"
alt="TanStack Angular Query"
width="900"
/>
</picture>
[![npm version](https://img.shields.io/npm/v/@tanstack/angular-query-experimental)](https://www.npmjs.com/package/@tanstack/angular-query-experimental)
[![npm license](https://img.shields.io/npm/l/@tanstack/angular-query-experimental)](https://github.com/TanStack/query/blob/main/LICENSE)
[![bundle size](https://img.shields.io/bundlephobia/minzip/@tanstack/angular-query-experimental)](https://bundlephobia.com/package/@tanstack/angular-query-experimental)
[![npm](https://img.shields.io/npm/dm/@tanstack/angular-query-experimental)](https://www.npmjs.com/package/@tanstack/angular-query-experimental)
# Angular Query
> IMPORTANT: This library is currently in an experimental stage. This means that breaking changes may happen in minor AND patch releases. Upgrade carefully. If you use this in production while in experimental stage, please lock your version to a patch-level version to avoid unexpected breaking changes.
Functions for fetching, caching and updating asynchronous data in Angular
# Documentation
Visit https://tanstack.com/query/latest/docs/framework/angular/overview
## Quick Features
- Transport/protocol/backend agnostic data fetching (REST, GraphQL, promises, whatever!)
- Auto Caching + Refetching (stale-while-revalidate, Window Refocus, Polling/Realtime)
- Parallel + Dependent Queries
- Mutations + Reactive Query Refetching
- Multi-layer Cache + Automatic Garbage Collection
- Paginated + Cursor-based Queries
- Load-More + Infinite Scroll Queries w/ Scroll Recovery
- Request Cancellation
- Dedicated Devtools
# Quick Start
> The Angular adapter for TanStack Query requires Angular 16 or higher.
1. Install `angular-query`
```bash
$ npm i @tanstack/angular-query-experimental
```
or
```bash
$ pnpm add @tanstack/angular-query-experimental
```
or
```bash
$ yarn add @tanstack/angular-query-experimental
```
or
```bash
$ bun add @tanstack/angular-query-experimental
```
2. Initialize **TanStack Query** by adding **provideTanStackQuery** to your application
```ts
import { provideTanStackQuery } from '@tanstack/angular-query-experimental'
import { QueryClient } from '@tanstack/angular-query-experimental'
bootstrapApplication(AppComponent, {
providers: [provideTanStackQuery(new QueryClient())],
})
```
or in a NgModule-based app
```ts
import { provideHttpClient } from '@angular/common/http'
import {
provideTanStackQuery,
QueryClient,
} from '@tanstack/angular-query-experimental'
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [provideTanStackQuery(new QueryClient())],
bootstrap: [AppComponent],
})
```
3. Inject query
```ts
import { injectQuery } from '@tanstack/angular-query-experimental'
import { Component } from '@angular/core'
@Component({...})
export class TodosComponent {
info = injectQuery(() => ({ queryKey: ['todos'], queryFn: fetchTodoList }))
}
```
4. If you need to update options on your query dynamically, make sure to pass them as signals. The query will refetch automatically if data for an updated query key is stale or not present.
[Open in StackBlitz](https://stackblitz.com/github/TanStack/query/tree/main/examples/angular/router)
```ts
@Component({})
export class PostComponent {
#postsService = inject(PostsService)
postId = input.required({
transform: numberAttribute,
})
postQuery = injectQuery(() => ({
queryKey: ['post', this.postId()],
queryFn: () => {
return lastValueFrom(this.#postsService.postById$(this.postId()))
},
}))
}
@Injectable({
providedIn: 'root',
})
export class PostsService {
#http = inject(HttpClient)
postById$ = (postId: number) =>
this.#http.get<Post>(`https://jsonplaceholder.typicode.com/posts/${postId}`)
}
export interface Post {
id: number
title: string
body: string
}
```
<!-- -->

View File

@@ -0,0 +1,24 @@
// @ts-check
import vitest from '@vitest/eslint-plugin'
import rootConfig from './root.eslint.config.js'
export default [
...rootConfig,
{
plugins: { vitest },
rules: {
'vitest/expect-expect': [
'error',
{ assertFunctionNames: ['expect', 'expectSignals'] },
],
},
},
{
files: ['**/__tests__/**'],
rules: {
'@typescript-eslint/no-unnecessary-condition': 'off',
'@typescript-eslint/require-await': 'off',
},
},
]

View File

@@ -0,0 +1,112 @@
{
"name": "@tanstack/angular-query-experimental",
"version": "5.102.8",
"description": "Signals for managing, caching and syncing asynchronous and remote data in Angular",
"author": "Arnoud de Vries",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/TanStack/query.git",
"directory": "packages/angular-query-experimental"
},
"homepage": "https://tanstack.com/query",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"keywords": [
"angular query",
"angular",
"cache",
"performance",
"reactive",
"rxjs",
"signals",
"state management",
"state",
"tanstack"
],
"scripts": {
"clean": "premove ./dist ./coverage ./dist-ts ./.cache/test-types",
"compile": "tsc --project tsconfig.json",
"test:eslint": "eslint --concurrency=auto ./src",
"test:types": "npm-run-all --serial test:types:*",
"test:types:ts56": "node ../../node_modules/typescript56/lib/tsc.js --project tsconfig.json --outDir .cache/test-types/ts56 --tsBuildInfoFile .cache/test-types/ts56.tsbuildinfo",
"test:types:ts57": "node ../../node_modules/typescript57/lib/tsc.js --project tsconfig.json --outDir .cache/test-types/ts57 --tsBuildInfoFile .cache/test-types/ts57.tsbuildinfo",
"test:types:ts58": "node ../../node_modules/typescript58/lib/tsc.js --project tsconfig.json --outDir .cache/test-types/ts58 --tsBuildInfoFile .cache/test-types/ts58.tsbuildinfo",
"test:types:ts59": "node ../../node_modules/typescript59/lib/tsc.js --project tsconfig.json --outDir .cache/test-types/ts59 --tsBuildInfoFile .cache/test-types/ts59.tsbuildinfo",
"test:types:tscurrent": "tsc --project tsconfig.json --outDir .cache/test-types/tscurrent --tsBuildInfoFile .cache/test-types/tscurrent.tsbuildinfo",
"test:types:ts70": "node ../../node_modules/typescript70/lib/tsc.js --project tsconfig.json --outDir .cache/test-types/ts70 --tsBuildInfoFile .cache/test-types/ts70.tsbuildinfo",
"test:lib": "vitest",
"test:lib:dev": "pnpm run test:lib --watch",
"test:build": "pnpm pack && publint ./dist/*.tgz --strict && attw ./dist/*.tgz; premove ./dist/*.tgz",
"build": "vite build",
"prepack": "node scripts/prepack.js"
},
"type": "module",
"types": "dist/index.d.ts",
"module": "dist/index.mjs",
"exports": {
".": {
"@tanstack/custom-condition": "./src/index.ts",
"types": "./dist/index.d.ts",
"default": "./dist/index.mjs"
},
"./package.json": "./package.json",
"./inject-queries-experimental": {
"types": "./dist/inject-queries-experimental/index.d.ts",
"default": "./dist/inject-queries-experimental/index.mjs"
},
"./devtools": {
"types": "./dist/devtools/index.d.ts",
"development": "./dist/devtools/index.mjs",
"default": "./dist/devtools/stub.mjs"
},
"./devtools/production": {
"types": "./dist/devtools/production/index.d.ts",
"default": "./dist/devtools/index.mjs"
},
"./devtools-panel": {
"types": "./dist/devtools-panel/index.d.ts",
"development": "./dist/devtools-panel/index.mjs",
"default": "./dist/devtools-panel/stub.mjs"
},
"./devtools-panel/production": {
"types": "./dist/devtools-panel/production/index.d.ts",
"default": "./dist/devtools-panel/index.mjs"
}
},
"sideEffects": false,
"files": [
"**/*.d.ts",
"**/*.mjs",
"**/*.mjs.map"
],
"dependencies": {
"@tanstack/query-core": "workspace:*"
},
"devDependencies": {
"@angular/common": "^20.0.0",
"@angular/compiler": "^20.0.0",
"@angular/core": "^20.0.0",
"@angular/platform-browser": "^20.0.0",
"@tanstack/query-test-utils": "workspace:*",
"@testing-library/angular": "^18.0.0",
"npm-run-all2": "^5.0.0",
"rxjs": "^7.8.2",
"vite-plugin-dts": "4.2.3",
"vite-plugin-externalize-deps": "^0.9.0",
"vite-tsconfig-paths": "^5.1.4"
},
"optionalDependencies": {
"@tanstack/query-devtools": "workspace:*"
},
"peerDependencies": {
"@angular/common": ">=16.0.0",
"@angular/core": ">=16.0.0"
},
"publishConfig": {
"directory": "dist",
"linkDirectory": false
}
}

View File

@@ -0,0 +1 @@
../../eslint.config.js

View File

@@ -0,0 +1,106 @@
import fs from 'node:fs'
import path from 'node:path'
/**
* Prepack script that prepares the package for publishing by:
* 1. Creating a modified package.json without dev dependencies, publishConfig and build scripts
* 2. Updating file paths to remove 'dist/' prefixes (since files will be at root in published package)
* 3. Writing this modified package.json to the `dist` directory
* 4. Copying additional files like README.md to the dist directory
*
* Type declarations need to be in the package root or corresponding sub-path to support
* sub-path exports in applications still using `moduleResolution: node`.
*/
console.log('Running prepack script')
/**
* Files to copy to the dist directory
* @type {string[]}
*/
const FILES_TO_COPY = ['README.md']
/**
* Fields to remove from the package.json copy
* @type {string[]}
*/
const FIELDS_TO_REMOVE = [
'devDependencies',
'files',
'publishConfig',
'scripts',
]
/**
* Replaces 'dist/' or './dist/' prefix from a file path with './'
* Only matches at the start of the path to avoid false matches
* @param {string} filePath - The file path to process
* @returns {string} The path without dist prefix
*/
function replaceDist(filePath) {
// Only match dist/ at the beginning of the path, followed by a filename
// This prevents matching strings like "distributed/file.js" or "some/dist/path"
return filePath.replace(/^(?:\.\/)?dist\/(?=.+)/, './')
}
/**
* Recursively processes package.json `exports` to remove dist prefixes
* @param {Record<string, any>} exports - The exports object to process
* @returns {Record<string, any>} The processed exports object
*/
function processExports(exports) {
return Object.fromEntries(
Object.entries(exports).map(([key, value]) => [
key,
typeof value === 'string'
? replaceDist(value)
: typeof value === 'object' && value !== null
? processExports(value)
: value,
]),
)
}
console.log('Copying modified package.json')
/** @type {Record<string, any>} */
const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'))
const modifiedPackageJson = { ...packageJson }
if (modifiedPackageJson.types) {
modifiedPackageJson.types = replaceDist(modifiedPackageJson.types)
}
if (modifiedPackageJson.module) {
modifiedPackageJson.module = replaceDist(modifiedPackageJson.module)
}
if (modifiedPackageJson.exports) {
modifiedPackageJson.exports = processExports(modifiedPackageJson.exports)
}
for (const field of FIELDS_TO_REMOVE) {
delete modifiedPackageJson[field]
}
if (!fs.existsSync('dist')) {
fs.mkdirSync('dist', { recursive: true })
}
fs.writeFileSync(
path.join('dist', 'package.json'),
JSON.stringify(modifiedPackageJson, null, 2),
)
console.log('Copying other files')
for (const file of FILES_TO_COPY) {
if (fs.existsSync(file)) {
fs.copyFileSync(file, path.join('dist', file))
console.log(`${file}`)
} else {
console.log(`${file} not found, skipping`)
}
}
console.log('prepack complete')

View File

@@ -0,0 +1,315 @@
import { assertType, describe, expectTypeOf, it } from 'vitest'
import { queryKey } from '@tanstack/query-test-utils'
import { QueryClient, dataTagSymbol, skipToken } from '@tanstack/query-core'
import { infiniteQueryOptions } from '../infinite-query-options'
import { injectInfiniteQuery } from '../inject-infinite-query'
import { injectQuery } from '../inject-query'
import type {
DataTag,
InfiniteData,
InitialDataFunction,
} from '@tanstack/query-core'
// Regression test for exported infiniteQueryOptions inference under declaration emit.
// TypeScript should be able to name the return type without expanding the
// internal data tag symbols into the consumer's .d.ts output.
export const exportedInfiniteQueryOptions = infiniteQueryOptions({
queryKey: ['invalid'],
getNextPageParam: () => 1,
initialPageParam: 1,
})
describe('infiniteQueryOptions', () => {
it('should not allow excess properties', () => {
const key = queryKey()
assertType(
infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('data'),
getNextPageParam: () => 1,
initialPageParam: 1,
// @ts-expect-error this is a good error, because stallTime does not exist!
stallTime: 1000,
}),
)
})
it('should infer types for callbacks', () => {
const key = queryKey()
infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('data'),
staleTime: 1000,
getNextPageParam: () => 1,
initialPageParam: 1,
select: (data) => {
expectTypeOf(data).toEqualTypeOf<InfiniteData<string, number>>()
},
})
})
it('should work when passed to useInfiniteQuery', () => {
const key = queryKey()
const options = infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
})
const { data } = injectInfiniteQuery(() => options)
// known issue: type of pageParams is unknown when returned from useInfiniteQuery
expectTypeOf(data()).toEqualTypeOf<
InfiniteData<string, unknown> | undefined
>()
})
it('should work when passed to fetchInfiniteQuery', async () => {
const key = queryKey()
const options = infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
})
// grandfathered direct test
// eslint-disable-next-line no-restricted-syntax
const data = await new QueryClient().fetchInfiniteQuery(options)
expectTypeOf(data).toEqualTypeOf<InfiniteData<string, number>>()
})
it('should work when passed to infiniteQuery', async () => {
const options = infiniteQueryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
})
const data = await new QueryClient().infiniteQuery(options)
expectTypeOf(data).toEqualTypeOf<InfiniteData<string, number>>()
})
it('should work when passed to infiniteQuery with select', async () => {
const options = infiniteQueryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
select: (data) => data.pages,
})
const data = await new QueryClient().infiniteQuery(options)
expectTypeOf(data).toEqualTypeOf<Array<string>>()
})
it('should work when passed to infiniteQuery with enabled: false', async () => {
const options = infiniteQueryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
enabled: false,
})
const data = await new QueryClient().infiniteQuery(options)
expectTypeOf(data).toEqualTypeOf<InfiniteData<string, number>>()
})
it('should work when passed to infiniteQuery with skipToken', async () => {
const options = infiniteQueryOptions({
queryKey: ['key'],
queryFn: skipToken,
getNextPageParam: () => 1,
initialPageParam: 1,
})
const data = await new QueryClient().infiniteQuery(options)
expectTypeOf(data).toEqualTypeOf<InfiniteData<unknown, number>>()
})
it('should tag the queryKey with the result type of the QueryFn', () => {
const key = queryKey()
const { queryKey: tagged } = infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
})
expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<InfiniteData<string>>()
})
it('should tag the queryKey even if no promise is returned', () => {
const key = queryKey()
const { queryKey: tagged } = infiniteQueryOptions({
queryKey: key,
queryFn: () => 'string',
getNextPageParam: () => 1,
initialPageParam: 1,
})
expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<InfiniteData<string>>()
})
it('should tag the queryKey with the result type of the QueryFn if select is used', () => {
const key = queryKey()
const { queryKey: tagged } = infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('string'),
select: (data) => data.pages,
getNextPageParam: () => 1,
initialPageParam: 1,
})
expectTypeOf(tagged[dataTagSymbol]).toEqualTypeOf<InfiniteData<string>>()
})
it('should return the proper type when passed to getQueryData', () => {
const key = queryKey()
const { queryKey: tagged } = infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
})
const queryClient = new QueryClient()
const data = queryClient.getQueryData(tagged)
expectTypeOf(data).toEqualTypeOf<
InfiniteData<string, unknown> | undefined
>()
})
it('should properly type when passed to setQueryData', () => {
const key = queryKey()
const { queryKey: tagged } = infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
})
const queryClient = new QueryClient()
const data = queryClient.setQueryData(tagged, (prev) => {
expectTypeOf(prev).toEqualTypeOf<
InfiniteData<string, unknown> | undefined
>()
return prev
})
expectTypeOf(data).toEqualTypeOf<
InfiniteData<string, unknown> | undefined
>()
})
it('should not be allowed to be passed to non-infinite query functions', () => {
const key = queryKey()
const queryClient = new QueryClient()
const options = infiniteQueryOptions({
queryKey: key,
queryFn: () => Promise.resolve('string'),
getNextPageParam: () => 1,
initialPageParam: 1,
})
assertType(
// @ts-expect-error cannot pass infinite options to non-infinite query functions
injectQuery(() => options),
)
assertType(
// @ts-expect-error cannot pass infinite options to non-infinite query functions
queryClient.query(options),
)
// deprecated methods below to be removed next major version
assertType(
// @ts-expect-error cannot pass infinite options to non-infinite query functions
// eslint-disable-next-line no-restricted-syntax -- grandfathered direct test
queryClient.ensureQueryData(options),
)
assertType(
// @ts-expect-error cannot pass infinite options to non-infinite query functions
// eslint-disable-next-line no-restricted-syntax -- grandfathered direct test
queryClient.fetchQuery(options),
)
assertType(
// @ts-expect-error cannot pass infinite options to non-infinite query functions
// eslint-disable-next-line no-restricted-syntax -- grandfathered direct test
queryClient.prefetchQuery(options),
)
})
it('should allow optional initialData function', () => {
const key = queryKey()
const initialData: { example: boolean } | undefined = { example: true }
const queryOptions = infiniteQueryOptions({
queryKey: key,
queryFn: () => initialData,
initialData: initialData
? () => ({ pages: [initialData], pageParams: [] })
: undefined,
getNextPageParam: () => 1,
initialPageParam: 1,
})
expectTypeOf(queryOptions.initialData).toExtend<
| InitialDataFunction<InfiniteData<{ example: boolean }, number>>
| InfiniteData<{ example: boolean }, number>
| undefined
>()
})
it('should allow optional initialData object', () => {
const key = queryKey()
const initialData: { example: boolean } | undefined = { example: true }
const queryOptions = infiniteQueryOptions({
queryKey: key,
queryFn: () => initialData,
initialData: initialData
? { pages: [initialData], pageParams: [] }
: undefined,
getNextPageParam: () => 1,
initialPageParam: 1,
})
expectTypeOf(queryOptions.initialData).toExtend<
| InitialDataFunction<InfiniteData<{ example: boolean }, number>>
| InfiniteData<{ example: boolean }, number>
| undefined
>()
})
it('should return a custom query key type', () => {
type MyQueryKey = [Array<string>, { type: 'foo' }]
const options = infiniteQueryOptions({
queryKey: [['key'], { type: 'foo' }] as MyQueryKey,
queryFn: () => Promise.resolve(1),
getNextPageParam: () => 1,
initialPageParam: 1,
})
expectTypeOf(options.queryKey).toEqualTypeOf<
DataTag<MyQueryKey, InfiniteData<number>, Error>
>()
})
it('should return a custom query key type with datatag', () => {
type MyQueryKey = DataTag<
[Array<string>, { type: 'foo' }],
number,
Error & { myMessage: string }
>
const options = infiniteQueryOptions({
queryKey: [['key'], { type: 'foo' }] as MyQueryKey,
queryFn: () => Promise.resolve(1),
getNextPageParam: () => 1,
initialPageParam: 1,
})
expectTypeOf(options.queryKey).toEqualTypeOf<
DataTag<MyQueryKey, InfiniteData<number>, Error & { myMessage: string }>
>()
})
})

View File

@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest'
import { queryKey } from '@tanstack/query-test-utils'
import { infiniteQueryOptions } from '../infinite-query-options'
import type { CreateInfiniteQueryOptions } from '../types'
describe('infiniteQueryOptions', () => {
it('should return the object received as a parameter without any modification.', () => {
const key = queryKey()
const object: CreateInfiniteQueryOptions = {
queryKey: key,
queryFn: () => Promise.resolve(5),
getNextPageParam: () => null,
initialPageParam: null,
}
expect(infiniteQueryOptions(object)).toBe(object)
})
})

View File

@@ -0,0 +1,196 @@
import {
ElementRef,
provideZonelessChangeDetection,
signal,
} from '@angular/core'
import { TestBed } from '@angular/core/testing'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient } from '@tanstack/query-core'
import { provideTanStackQuery } from '../providers'
import { injectDevtoolsPanel } from '../devtools-panel'
const mockDevtoolsPanelInstance = {
mount: vi.fn(),
unmount: vi.fn(),
setClient: vi.fn(),
setErrorTypes: vi.fn(),
setOnClose: vi.fn(),
}
const mocks = vi.hoisted(() => {
function MockTanstackQueryDevtoolsPanel() {
return mockDevtoolsPanelInstance
}
return {
mockTanstackQueryDevtoolsPanel: vi.fn(MockTanstackQueryDevtoolsPanel),
}
})
vi.mock('@tanstack/query-devtools', () => ({
TanstackQueryDevtoolsPanel: mocks.mockTanstackQueryDevtoolsPanel,
}))
describe('injectDevtoolsPanel', () => {
let queryClient: QueryClient
let mockElementRef: ElementRef
const waitForDevtoolsToBeCreated = async () => {
await vi.waitFor(() => {
expect(mocks.mockTanstackQueryDevtoolsPanel).toHaveBeenCalledTimes(1)
})
}
beforeEach(() => {
vi.clearAllMocks()
queryClient = new QueryClient()
mockElementRef = new ElementRef(document.createElement('div'))
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
{ provide: ElementRef, useValue: signal(mockElementRef) },
],
})
})
afterEach(() => {
vi.restoreAllMocks()
})
it('should return a DevtoolsPanelRef', () => {
const result = TestBed.runInInjectionContext(() => {
return injectDevtoolsPanel(() => ({
hostElement: TestBed.inject(ElementRef),
}))
})
expect(result).toEqual({
destroy: expect.any(Function),
})
})
it('should initialize TanstackQueryDevtoolsPanel', async () => {
TestBed.runInInjectionContext(() => {
injectDevtoolsPanel(() => ({
hostElement: TestBed.inject(ElementRef),
}))
})
TestBed.tick()
await waitForDevtoolsToBeCreated()
expect(mockDevtoolsPanelInstance.mount).toHaveBeenCalledTimes(1)
})
it('should destroy TanstackQueryDevtoolsPanel', async () => {
const result = TestBed.runInInjectionContext(() => {
return injectDevtoolsPanel(() => ({
hostElement: TestBed.inject(ElementRef),
}))
})
TestBed.tick()
await waitForDevtoolsToBeCreated()
result.destroy()
expect(mockDevtoolsPanelInstance.unmount).toHaveBeenCalledTimes(1)
})
it('should destroy TanstackQueryDevtoolsPanel when hostElement is removed', async () => {
const hostElement = signal<ElementRef>(mockElementRef)
TestBed.runInInjectionContext(() => {
return injectDevtoolsPanel(() => ({
hostElement: hostElement(),
}))
})
TestBed.tick()
await waitForDevtoolsToBeCreated()
expect(mockDevtoolsPanelInstance.unmount).toHaveBeenCalledTimes(0)
hostElement.set(null as unknown as ElementRef)
TestBed.tick()
expect(mockDevtoolsPanelInstance.unmount).toHaveBeenCalledTimes(1)
})
it('should update client', async () => {
const client = signal(new QueryClient())
TestBed.runInInjectionContext(() => {
return injectDevtoolsPanel(() => ({
hostElement: TestBed.inject(ElementRef),
client: client(),
}))
})
TestBed.tick()
await waitForDevtoolsToBeCreated()
expect(mockDevtoolsPanelInstance.setClient).toHaveBeenCalledTimes(0)
client.set(new QueryClient())
TestBed.tick()
expect(mockDevtoolsPanelInstance.setClient).toHaveBeenCalledTimes(1)
})
it('should update error types', async () => {
const errorTypes = signal([])
TestBed.runInInjectionContext(() => {
return injectDevtoolsPanel(() => ({
hostElement: TestBed.inject(ElementRef),
errorTypes: errorTypes(),
}))
})
TestBed.tick()
await waitForDevtoolsToBeCreated()
expect(mockDevtoolsPanelInstance.setErrorTypes).toHaveBeenCalledTimes(0)
errorTypes.set([])
TestBed.tick()
expect(mockDevtoolsPanelInstance.setErrorTypes).toHaveBeenCalledTimes(1)
})
it('should update onclose', async () => {
const functionA = () => {}
const functionB = () => {}
const onClose = signal(functionA)
TestBed.runInInjectionContext(() => {
return injectDevtoolsPanel(() => ({
hostElement: TestBed.inject(ElementRef),
onClose: onClose(),
}))
})
TestBed.tick()
await waitForDevtoolsToBeCreated()
expect(mockDevtoolsPanelInstance.setOnClose).toHaveBeenCalledTimes(0)
onClose.set(functionB)
TestBed.tick()
expect(mockDevtoolsPanelInstance.setOnClose).toHaveBeenCalledTimes(1)
})
})

View File

@@ -0,0 +1,66 @@
import { TestBed } from '@angular/core/testing'
import { afterEach, beforeEach, describe, expectTypeOf, it, vi } from 'vitest'
import { provideZonelessChangeDetection } from '@angular/core'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import {
QueryClient,
injectInfiniteQuery,
provideTanStackQuery,
skipToken,
} from '..'
import type { InfiniteData } from '@tanstack/query-core'
describe('injectInfiniteQuery', () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = new QueryClient()
vi.useFakeTimers()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
it('should narrow type after isSuccess', () => {
const key = queryKey()
const query = TestBed.runInInjectionContext(() => {
return injectInfiniteQuery(() => ({
queryKey: key,
queryFn: ({ pageParam }) =>
sleep(0).then(() => 'data on page ' + pageParam),
initialPageParam: 0,
getNextPageParam: () => 12,
}))
})
if (query.isSuccess()) {
const data = query.data()
expectTypeOf(data).toEqualTypeOf<InfiniteData<string, unknown>>()
}
})
it('should work when queryFn is skipToken', () => {
const key = queryKey()
const query = TestBed.runInInjectionContext(() => {
return injectInfiniteQuery(() => ({
queryKey: key,
queryFn: skipToken,
initialPageParam: 0,
getNextPageParam: () => 1,
}))
})
// TPageParam falls back to `unknown` here (unlike `infiniteQueryOptions`, which infers
// `number` for the same options) because there's no skipToken-specific overload to carry it.
expectTypeOf(query.data()).toEqualTypeOf<
InfiniteData<unknown, unknown> | undefined
>()
})
})

View File

@@ -0,0 +1,227 @@
import { TestBed } from '@angular/core/testing'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
Component,
Injector,
provideZonelessChangeDetection,
signal,
} from '@angular/core'
import { render } from '@testing-library/angular'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import {
QueryClient,
injectInfiniteQuery,
provideTanStackQuery,
skipToken,
} from '..'
describe('injectInfiniteQuery', () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = new QueryClient()
vi.useFakeTimers()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
it('should properly execute infinite query', async () => {
const key = queryKey()
@Component({
template: `
<div>status: {{ query.status() }}</div>
<div>pages: {{ query.data()?.pages?.join(', ') ?? 'none' }}</div>
`,
})
class Page {
readonly query = injectInfiniteQuery(() => ({
queryKey: key,
queryFn: ({ pageParam }) =>
sleep(10).then(() => 'data on page ' + pageParam),
initialPageParam: 0,
getNextPageParam: () => 12,
}))
}
const rendered = await render(Page)
expect(rendered.getByText('status: pending')).toBeInTheDocument()
expect(rendered.getByText('pages: none')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('status: success')).toBeInTheDocument()
expect(rendered.getByText('pages: data on page 0')).toBeInTheDocument()
rendered.fixture.componentInstance.query.fetchNextPage()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('status: success')).toBeInTheDocument()
expect(
rendered.getByText('pages: data on page 0, data on page 12'),
).toBeInTheDocument()
})
it('should reject and update signal', async () => {
const key = queryKey()
@Component({
template: `
<div>status: {{ query.status() }}</div>
<div>pages: {{ query.data()?.pages?.join(', ') ?? 'none' }}</div>
<div>error: {{ query.error()?.message ?? 'none' }}</div>
<div>isError: {{ query.isError() }}</div>
<div>failureCount: {{ query.failureCount() }}</div>
`,
})
class Page {
readonly query = injectInfiniteQuery(() => ({
retry: false,
queryKey: key,
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
initialPageParam: 0,
getNextPageParam: () => 12,
}))
}
const rendered = await render(Page)
expect(rendered.getByText('status: pending')).toBeInTheDocument()
expect(rendered.getByText('pages: none')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('status: error')).toBeInTheDocument()
expect(rendered.getByText('pages: none')).toBeInTheDocument()
expect(rendered.getByText('error: Some error')).toBeInTheDocument()
expect(rendered.getByText('isError: true')).toBeInTheDocument()
expect(rendered.getByText('failureCount: 1')).toBeInTheDocument()
})
it('should keep initialData visible alongside the error when a refetch fails', async () => {
const key = queryKey()
@Component({
template: `
<div>pages: {{ query.data().pages.join(', ') }}</div>
<div>isError: {{ query.isError() }}</div>
`,
})
class Page {
readonly query = injectInfiniteQuery(() => ({
queryKey: key,
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
initialData: { pages: [1], pageParams: [1] },
getNextPageParam: (lastPage: number) => lastPage + 1,
initialPageParam: 0,
retry: false,
}))
}
const rendered = await render(Page)
expect(rendered.getByText('pages: 1')).toBeInTheDocument()
expect(rendered.getByText('isError: false')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('pages: 1')).toBeInTheDocument()
expect(rendered.getByText('isError: true')).toBeInTheDocument()
})
describe('skipToken', () => {
it('should not fetch when queryFn is skipToken, and fetch once it is replaced', async () => {
const key = queryKey()
const queryFn = vi.fn(({ pageParam }: { pageParam: number }) =>
sleep(10).then(() => `comments for 1 page ${pageParam}`),
)
@Component({
template: `
<div>status: {{ query.status() }}</div>
<div>isFetching: {{ query.isFetching() }}</div>
<div>pages: {{ query.data()?.pages?.join(', ') ?? 'none' }}</div>
`,
})
class Page {
postId = signal<string | undefined>(undefined)
readonly query = injectInfiniteQuery(() => ({
queryKey: key,
queryFn: this.postId() != null ? queryFn : skipToken,
initialPageParam: 0,
getNextPageParam: () => 12,
}))
}
const rendered = await render(Page)
expect(rendered.getByText('status: pending')).toBeInTheDocument()
expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(queryFn).not.toHaveBeenCalled()
expect(rendered.getByText('status: pending')).toBeInTheDocument()
expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
rendered.fixture.componentInstance.postId.set('1')
rendered.fixture.detectChanges()
expect(rendered.getByText('isFetching: true')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(queryFn).toHaveBeenCalledTimes(1)
expect(rendered.getByText('status: success')).toBeInTheDocument()
expect(
rendered.getByText('pages: comments for 1 page 0'),
).toBeInTheDocument()
})
})
describe('injection context', () => {
it('should throw NG0203 with descriptive error outside injection context', () => {
const key = queryKey()
expect(() => {
injectInfiniteQuery(() => ({
queryKey: key,
queryFn: ({ pageParam }) =>
sleep(0).then(() => 'data on page ' + pageParam),
initialPageParam: 0,
getNextPageParam: () => 12,
}))
}).toThrow(/NG0203(.*?)injectInfiniteQuery/)
})
it('should be usable outside injection context when passing an injector', () => {
const key = queryKey()
const query = injectInfiniteQuery(
() => ({
queryKey: key,
queryFn: ({ pageParam }) =>
sleep(0).then(() => 'data on page ' + pageParam),
initialPageParam: 0,
getNextPageParam: () => 12,
}),
{
injector: TestBed.inject(Injector),
},
)
expect(query.status()).toBe('pending')
})
})
})

View File

@@ -0,0 +1,108 @@
import { TestBed } from '@angular/core/testing'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
Component,
Injector,
provideZonelessChangeDetection,
} from '@angular/core'
import { render } from '@testing-library/angular'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import {
QueryClient,
injectIsFetching,
injectQuery,
provideTanStackQuery,
} from '..'
describe('injectIsFetching', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryClient = new QueryClient()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
it('should return the number of fetching queries', async () => {
const key = queryKey()
@Component({
template: `<div>fetching: {{ isFetching() }}</div>`,
})
class Page {
readonly query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(100).then(() => 'Some data'),
}))
readonly isFetching = injectIsFetching()
}
const rendered = await render(Page)
expect(rendered.getByText('fetching: 0')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(0)
rendered.fixture.detectChanges()
expect(rendered.getByText('fetching: 1')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(101)
rendered.fixture.detectChanges()
expect(rendered.getByText('fetching: 0')).toBeInTheDocument()
})
it('should be able to filter by queryKey', async () => {
const key1 = queryKey()
const key2 = queryKey()
@Component({
template: `<div>fetching: {{ isFetching() }}</div>`,
})
class Page {
readonly query1 = injectQuery(() => ({
queryKey: key1,
queryFn: () => sleep(10).then(() => 'test1'),
}))
readonly query2 = injectQuery(() => ({
queryKey: key2,
queryFn: () => sleep(100).then(() => 'test2'),
}))
readonly isFetching = injectIsFetching({ queryKey: key1 })
}
const rendered = await render(Page)
await vi.advanceTimersByTimeAsync(0)
rendered.fixture.detectChanges()
expect(rendered.getByText('fetching: 1')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('fetching: 0')).toBeInTheDocument()
})
describe('injection context', () => {
it('should throw NG0203 with descriptive error outside injection context', () => {
expect(() => {
injectIsFetching()
}).toThrow(/NG0203(.*?)injectIsFetching/)
})
it('should be usable outside injection context when passing an injector', () => {
expect(
injectIsFetching(undefined, {
injector: TestBed.inject(Injector),
}),
).not.toThrow()
})
})
})

View File

@@ -0,0 +1,113 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { TestBed } from '@angular/core/testing'
import {
Component,
Injector,
provideZonelessChangeDetection,
} from '@angular/core'
import { render } from '@testing-library/angular'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import {
QueryClient,
injectIsMutating,
injectMutation,
provideTanStackQuery,
} from '..'
describe('injectIsMutating', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryClient = new QueryClient()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
it('should properly return isMutating state', async () => {
const key = queryKey()
@Component({
template: `<div>mutating: {{ isMutating() }}</div>`,
})
class Page {
readonly mutation = injectMutation(() => ({
mutationKey: key,
mutationFn: (params: { par1: string }) => sleep(10).then(() => params),
}))
readonly isMutating = injectIsMutating()
}
const rendered = await render(Page)
expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
rendered.fixture.componentInstance.mutation.mutate({ par1: 'par1' })
await vi.advanceTimersByTimeAsync(0)
rendered.fixture.detectChanges()
expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
})
it('should be able to filter by mutationKey', async () => {
const key1 = queryKey()
const key2 = queryKey()
@Component({
template: `<div>mutating: {{ isMutating() }}</div>`,
})
class Page {
readonly mutation1 = injectMutation(() => ({
mutationKey: key1,
mutationFn: () => sleep(10).then(() => 'data1'),
}))
readonly mutation2 = injectMutation(() => ({
mutationKey: key2,
mutationFn: () => sleep(100).then(() => 'data2'),
}))
readonly isMutating = injectIsMutating({ mutationKey: key1 })
}
const rendered = await render(Page)
rendered.fixture.componentInstance.mutation1.mutate()
rendered.fixture.componentInstance.mutation2.mutate()
await vi.advanceTimersByTimeAsync(0)
rendered.fixture.detectChanges()
expect(rendered.getByText('mutating: 1')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('mutating: 0')).toBeInTheDocument()
})
describe('injection context', () => {
it('should throw NG0203 with descriptive error outside injection context', () => {
expect(() => {
injectIsMutating()
}).toThrow(/NG0203(.*?)injectIsMutating/)
})
it('should be usable outside injection context when passing an injector', () => {
expect(
injectIsMutating(undefined, {
injector: TestBed.inject(Injector),
}),
).not.toThrow()
})
})
})

View File

@@ -0,0 +1,93 @@
import { TestBed } from '@angular/core/testing'
import { beforeEach, describe, expect, it } from 'vitest'
import { Injector, provideZonelessChangeDetection, signal } from '@angular/core'
import {
QueryClient,
injectIsRestoring,
provideIsRestoring,
provideTanStackQuery,
} from '..'
describe('injectIsRestoring', () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = new QueryClient()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
it('should return false by default when provideIsRestoring is not used', () => {
const isRestoring = TestBed.runInInjectionContext(() => {
return injectIsRestoring()
})
expect(isRestoring()).toBe(false)
})
it('should return the provided signal value when provideIsRestoring is used', () => {
const restoringSignal = signal(true)
TestBed.configureTestingModule({
providers: [provideIsRestoring(restoringSignal.asReadonly())],
})
const isRestoring = TestBed.runInInjectionContext(() => {
return injectIsRestoring()
})
expect(isRestoring()).toBe(true)
})
it('should reactively reflect changes to the provided signal', () => {
const restoringSignal = signal(true)
TestBed.configureTestingModule({
providers: [provideIsRestoring(restoringSignal.asReadonly())],
})
const isRestoring = TestBed.runInInjectionContext(() => {
return injectIsRestoring()
})
expect(isRestoring()).toBe(true)
restoringSignal.set(false)
expect(isRestoring()).toBe(false)
restoringSignal.set(true)
expect(isRestoring()).toBe(true)
})
it('should be usable outside injection context when passing an injector', () => {
const isRestoring = injectIsRestoring({
injector: TestBed.inject(Injector),
})
expect(isRestoring()).toBe(false)
})
it('should return the provided signal value when using injector option', () => {
const restoringSignal = signal(true)
TestBed.configureTestingModule({
providers: [provideIsRestoring(restoringSignal.asReadonly())],
})
const isRestoring = injectIsRestoring({
injector: TestBed.inject(Injector),
})
expect(isRestoring()).toBe(true)
})
it('should throw NG0203 with descriptive error outside injection context', () => {
expect(() => {
injectIsRestoring()
}).toThrow(/NG0203(.*?)injectIsRestoring/)
})
})

View File

@@ -0,0 +1,22 @@
import { describe, expectTypeOf, it } from 'vitest'
import { injectMutationState } from '..'
import type { MutationState, MutationStatus } from '..'
describe('injectMutationState', () => {
it('should default to QueryState', () => {
const result = injectMutationState(() => ({
filters: { status: 'pending' },
}))
expectTypeOf(result()).toEqualTypeOf<Array<MutationState>>()
})
it('should infer with select', () => {
const result = injectMutationState(() => ({
filters: { status: 'pending' },
select: (mutation) => mutation.state.status,
}))
expectTypeOf(result()).toEqualTypeOf<Array<MutationStatus>>()
})
})

View File

@@ -0,0 +1,198 @@
import {
Component,
Injector,
input,
provideZonelessChangeDetection,
signal,
} from '@angular/core'
import { TestBed } from '@angular/core/testing'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { By } from '@angular/platform-browser'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import {
QueryClient,
injectMutation,
injectMutationState,
provideTanStackQuery,
} from '..'
import { setFixtureSignalInputs } from './test-utils'
describe('injectMutationState', () => {
let queryClient: QueryClient
beforeEach(() => {
queryClient = new QueryClient()
vi.useFakeTimers()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
describe('injectMutationState', () => {
it('should return variables after calling mutate 1', () => {
const mutationKey = queryKey()
const variables = 'foo123'
const mutation = TestBed.runInInjectionContext(() => {
return injectMutation(() => ({
mutationKey: mutationKey,
mutationFn: (params: string) => sleep(0).then(() => params),
}))
})
mutation.mutate(variables)
const mutationState = TestBed.runInInjectionContext(() => {
return injectMutationState(() => ({
filters: { mutationKey, status: 'pending' },
select: (m) => m.state.variables,
}))
})
expect(mutationState()).toEqual([variables])
})
it('should update injectMutationState when reactive options change', () => {
const mutationKey1 = queryKey()
const mutationKey2 = queryKey()
const variables1 = 'foo123'
const variables2 = 'bar234'
const [mutation1, mutation2] = TestBed.runInInjectionContext(() => {
return [
injectMutation(() => ({
mutationKey: mutationKey1,
mutationFn: (params: string) => sleep(0).then(() => params),
})),
injectMutation(() => ({
mutationKey: mutationKey2,
mutationFn: (params: string) => sleep(0).then(() => params),
})),
]
})
mutation1.mutate(variables1)
mutation2.mutate(variables2)
const filterKey = signal(mutationKey1)
const mutationState = TestBed.runInInjectionContext(() => {
return injectMutationState(() => ({
filters: { mutationKey: filterKey(), status: 'pending' },
select: (m) => m.state.variables,
}))
})
expect(mutationState()).toEqual([variables1])
filterKey.set(mutationKey2)
expect(mutationState()).toEqual([variables2])
})
it('should return variables after calling mutate 2', () => {
queryClient.clear()
const mutationKey = queryKey()
const variables = 'bar234'
const mutation = TestBed.runInInjectionContext(() => {
return injectMutation(() => ({
mutationKey: mutationKey,
mutationFn: (params: string) => sleep(0).then(() => params),
}))
})
mutation.mutate(variables)
const mutationState = TestBed.runInInjectionContext(() => {
return injectMutationState()
})
expect(mutationState()[0]?.variables).toEqual(variables)
})
it('should support required signal inputs', async () => {
queryClient.clear()
const fakeName = 'name1'
const mutationKey1 = ['fake', fakeName]
const mutations = TestBed.runInInjectionContext(() => {
return [
injectMutation(() => ({
mutationKey: mutationKey1,
mutationFn: () => sleep(10).then(() => 'myValue'),
})),
injectMutation(() => ({
mutationKey: mutationKey1,
mutationFn: () =>
sleep(10).then(() => Promise.reject(new Error('myValue2'))),
})),
]
})
mutations.forEach((mutation) => mutation.mutate())
@Component({
selector: 'app-fake',
template: `
@for (mutation of mutationState(); track $index) {
<span>{{ mutation.status }}</span>
}
`,
})
class FakeComponent {
name = input.required<string>()
mutationState = injectMutationState(() => ({
filters: {
mutationKey: ['fake', this.name()],
exact: true,
},
}))
}
const fixture = TestBed.createComponent(FakeComponent)
const { debugElement } = fixture
setFixtureSignalInputs(fixture, { name: fakeName })
await vi.advanceTimersByTimeAsync(0)
let spans = debugElement
.queryAll(By.css('span'))
.map((span) => span.nativeNode.textContent)
expect(spans).toEqual(['pending', 'pending'])
await vi.advanceTimersByTimeAsync(11)
fixture.detectChanges()
spans = debugElement
.queryAll(By.css('span'))
.map((span) => span.nativeNode.textContent)
expect(spans).toEqual(['success', 'error'])
})
describe('injection context', () => {
it('should throw NG0203 with descriptive error outside injection context', () => {
expect(() => {
injectMutationState()
}).toThrow(/NG0203(.*?)injectMutationState/)
})
it('should be usable outside injection context when passing an injector', () => {
const injector = TestBed.inject(Injector)
expect(
injectMutationState(undefined, {
injector,
}),
).not.toThrow()
})
})
})
})

View File

@@ -0,0 +1,158 @@
import { describe, expectTypeOf, it } from 'vitest'
import { sleep } from '@tanstack/query-test-utils'
import { injectMutation } from '..'
import type { Signal } from '@angular/core'
import type {
MutationFunctionContext,
MutationKey,
QueryClient,
} from '@tanstack/query-core'
describe('injectMutation', () => {
describe('Discriminated union return type', () => {
it('data should be possibly undefined by default', () => {
const mutation = injectMutation(() => ({
mutationFn: () => sleep(0).then(() => 'string'),
}))
expectTypeOf(mutation.data).toEqualTypeOf<Signal<string | undefined>>()
})
it('data should be defined when mutation is success', () => {
const mutation = injectMutation(() => ({
mutationFn: () => sleep(0).then(() => 'string'),
}))
if (mutation.isSuccess()) {
expectTypeOf(mutation.data).toEqualTypeOf<Signal<string>>()
}
})
it('error should be null when mutation is success', () => {
const mutation = injectMutation(() => ({
mutationFn: () => sleep(0).then(() => 'string'),
}))
if (mutation.isSuccess()) {
expectTypeOf(mutation.error).toEqualTypeOf<Signal<null>>()
}
})
it('data should be undefined when mutation is pending', () => {
const mutation = injectMutation(() => ({
mutationFn: () => sleep(0).then(() => 'string'),
}))
if (mutation.isPending()) {
expectTypeOf(mutation.data).toEqualTypeOf<Signal<undefined>>()
}
})
it('error should be defined when mutation is error', () => {
const mutation = injectMutation(() => ({
mutationFn: () => sleep(0).then(() => 'string'),
}))
if (mutation.isError()) {
expectTypeOf(mutation.error).toEqualTypeOf<Signal<Error>>()
}
})
it('should narrow variables', () => {
const mutation = injectMutation(() => ({
mutationFn: (_variables: string) => sleep(0).then(() => 'string'),
}))
if (mutation.isIdle()) {
expectTypeOf(mutation.variables).toEqualTypeOf<Signal<undefined>>()
}
if (mutation.isPending()) {
expectTypeOf(mutation.variables).toEqualTypeOf<Signal<string>>()
}
if (mutation.isSuccess()) {
expectTypeOf(mutation.variables).toEqualTypeOf<Signal<string>>()
}
expectTypeOf(mutation.variables).toEqualTypeOf<
Signal<string | undefined>
>()
})
})
it('should infer TOnMutateResult from onMutate return type', () => {
injectMutation(() => ({
mutationFn: () => sleep(0).then(() => 'string'),
onMutate: () => {
return { token: 'abc' }
},
onSuccess: (_data, _variables, onMutateResult) => {
expectTypeOf(onMutateResult).toEqualTypeOf<{ token: string }>()
},
onError: (_error, _variables, onMutateResult) => {
expectTypeOf(onMutateResult).toEqualTypeOf<
{ token: string } | undefined
>()
},
}))
})
it('should allow calling mutate with no arguments when TVariables is optional undefinable', () => {
const mutation = injectMutation(() => ({
mutationFn: (_variables: number | undefined) => sleep(0).then(() => 1),
}))
expectTypeOf(mutation.mutate).toBeCallableWith()
expectTypeOf(mutation.mutateAsync).toBeCallableWith()
})
it('should type context as the last argument for mutationFn and every hook-level callback', () => {
injectMutation(() => ({
mutationFn: (_variables, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
expectTypeOf(context.client).toEqualTypeOf<QueryClient>()
return Promise.resolve('data')
},
onMutate: (_variables, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSuccess: (_data, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onError: (_error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSettled: (_data, _error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
}))
})
it('should type context as the last argument for every per-call mutate option', () => {
const mutation = injectMutation(() => ({
mutationFn: () => Promise.resolve('data'),
}))
mutation.mutate(undefined, {
onSuccess: (_data, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onError: (_error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSettled: (_data, _error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
})
})
it('should type context.mutationKey as MutationKey', () => {
injectMutation(() => ({
mutationKey: ['todos', 'add'] as const,
mutationFn: () => Promise.resolve('data'),
onSuccess: (_data, _variables, _onMutateResult, context) => {
expectTypeOf(context.mutationKey).toEqualTypeOf<
MutationKey | undefined
>()
},
}))
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,196 @@
import { describe, expectTypeOf, it } from 'vitest'
import { queryKey } from '@tanstack/query-test-utils'
import { skipToken } from '..'
import { injectQueries } from '../inject-queries'
import { queryOptions } from '../query-options'
import type { CreateQueryOptions, CreateQueryResult, OmitKeyof } from '..'
import type { Signal } from '@angular/core'
describe('injectQueries', () => {
describe('config object overload', () => {
it('TData should always be defined when initialData is provided as an object', () => {
const key1 = queryKey()
const key2 = queryKey()
const key3 = queryKey()
const query1 = {
queryKey: key1,
queryFn: () => {
return {
wow: true,
}
},
initialData: {
wow: false,
},
}
const query2 = {
queryKey: key2,
queryFn: () => 'Query Data',
initialData: 'initial data',
}
const query3 = {
queryKey: key3,
queryFn: () => 'Query Data',
}
const queryResults = injectQueries(() => ({
queries: [query1, query2, query3],
}))
const query1Data = queryResults()[0].data()
const query2Data = queryResults()[1].data()
const query3Data = queryResults()[2].data()
expectTypeOf(query1Data).toEqualTypeOf<{ wow: boolean }>()
expectTypeOf(query2Data).toEqualTypeOf<string>()
expectTypeOf(query3Data).toEqualTypeOf<string | undefined>()
})
it('TData should be defined when passed through queryOptions', () => {
const key = queryKey()
const options = queryOptions({
queryKey: key,
queryFn: () => {
return {
wow: true,
}
},
initialData: {
wow: true,
},
})
const queryResults = injectQueries(() => ({ queries: [options] }))
const data = queryResults()[0].data()
expectTypeOf(data).toEqualTypeOf<{ wow: boolean }>()
})
it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into injectQuery', () => {
const key1 = queryKey()
const key2 = queryKey()
const query1 = queryOptions({
queryKey: key1,
queryFn: () => Promise.resolve(1),
select: (data) => data > 1,
})
const query2 = {
queryKey: key2,
queryFn: () => Promise.resolve(1),
select: (data: number) => data > 1,
}
const queryResults = injectQueries(() => ({ queries: [query1, query2] }))
const query1Data = queryResults()[0].data()
const query2Data = queryResults()[1].data()
expectTypeOf(query1Data).toEqualTypeOf<boolean | undefined>()
expectTypeOf(query2Data).toEqualTypeOf<boolean | undefined>()
})
it('TData should have undefined in the union when initialData is provided as a function which can return undefined', () => {
const key = queryKey()
const queryResults = injectQueries(() => ({
queries: [
{
queryKey: key,
queryFn: () => {
return {
wow: true,
}
},
initialData: () => undefined as { wow: boolean } | undefined,
},
],
}))
const data = queryResults()[0].data()
expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
})
describe('custom injectable', () => {
it('should allow custom hooks using UseQueryOptions', () => {
type Data = string
const key = queryKey()
const injectCustomQueries = (
options?: OmitKeyof<CreateQueryOptions<Data>, 'queryKey' | 'queryFn'>,
) => {
return injectQueries(() => ({
queries: [
{
...options,
queryKey: key,
queryFn: () => Promise.resolve('data'),
},
],
}))
}
const queryResults = injectCustomQueries()
const data = queryResults()[0].data()
expectTypeOf(data).toEqualTypeOf<Data | undefined>()
})
})
it('TData should have correct type when conditional skipToken is passed', () => {
const key = queryKey()
const queryResults = injectQueries(() => ({
queries: [
{
queryKey: key,
queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5),
},
],
}))
const firstResult = queryResults()[0]
expectTypeOf(firstResult).toEqualTypeOf<
CreateQueryResult<number, Error>
>()
expectTypeOf(firstResult.data()).toEqualTypeOf<number | undefined>()
})
it('should return correct data for dynamic queries with mixed result types', () => {
const key1 = queryKey()
const key2 = queryKey()
const Queries1 = {
get: () =>
queryOptions({
queryKey: key1,
queryFn: () => Promise.resolve(1),
}),
}
const Queries2 = {
get: () =>
queryOptions({
queryKey: key2,
queryFn: () => Promise.resolve(true),
}),
}
const queries1List = [1, 2, 3].map(() => ({ ...Queries1.get() }))
const result = injectQueries(() => ({
queries: [...queries1List, { ...Queries2.get() }],
}))
expectTypeOf(result).branded.toEqualTypeOf<
Signal<
[
...Array<CreateQueryResult<number, Error>>,
CreateQueryResult<boolean, Error>,
]
>
>()
})
})
})

View File

@@ -0,0 +1,240 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
Component,
effect,
provideZonelessChangeDetection,
signal,
} from '@angular/core'
import { TestBed } from '@angular/core/testing'
import { render } from '@testing-library/angular'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import { QueryClient, provideIsRestoring, provideTanStackQuery } from '..'
import { injectQueries } from '../inject-queries'
describe('injectQueries', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryClient = new QueryClient()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
it('should return the correct states', async () => {
const key1 = queryKey()
const key2 = queryKey()
const results: Array<Array<Record<string, any>>> = []
@Component({
template: `
<div>
<div>
data1: {{ result()[0].data() ?? 'null' }}, data2:
{{ result()[1].data() ?? 'null' }}
</div>
</div>
`,
})
class Page {
readonly result = injectQueries(() => ({
queries: [
{
queryKey: key1,
queryFn: () => sleep(10).then(() => 1),
},
{
queryKey: key2,
queryFn: () => sleep(100).then(() => 2),
},
],
}))
constructor() {
effect(() => {
const snapshot = this.result().map((q) => ({ data: q.data() }))
results.push(snapshot)
})
}
}
const rendered = await render(Page)
await vi.advanceTimersByTimeAsync(101)
rendered.fixture.detectChanges()
expect(rendered.getByText('data1: 1, data2: 2')).toBeInTheDocument()
expect(results.length).toBe(3)
expect(results[0]).toMatchObject([{ data: undefined }, { data: undefined }])
expect(results[1]).toMatchObject([{ data: 1 }, { data: undefined }])
expect(results[2]).toMatchObject([{ data: 1 }, { data: 2 }])
})
it('should return the combined result when combine is provided', async () => {
const key1 = queryKey()
const key2 = queryKey()
const results: Array<Record<string, any>> = []
@Component({
template: `
<div>data: {{ combined().data.join(',') }}</div>
<div>isPending: {{ combined().isPending }}</div>
`,
})
class Page {
readonly combined = injectQueries(() => ({
queries: [
{
queryKey: key1,
queryFn: () => sleep(10).then(() => 1),
},
{
queryKey: key2,
queryFn: () => sleep(10).then(() => 2),
},
],
combine: (queries) => ({
data: queries.map((q) => q.data),
isPending: queries.some((q) => q.isPending),
}),
}))
constructor() {
effect(() => {
results.push({ ...this.combined() })
})
}
}
const rendered = await render(Page)
expect(rendered.getByText('data: ,')).toBeInTheDocument()
expect(rendered.getByText('isPending: true')).toBeInTheDocument()
expect(results[0]).toMatchObject({
data: [undefined, undefined],
isPending: true,
})
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('data: 1,2')).toBeInTheDocument()
expect(rendered.getByText('isPending: false')).toBeInTheDocument()
expect(results[results.length - 1]).toMatchObject({
data: [1, 2],
isPending: false,
})
expect(results.length).toBeGreaterThanOrEqual(2)
})
it('should reflect error state when one of the queries rejects', async () => {
const key1 = queryKey()
const key2 = queryKey()
@Component({
template: `
<div>
status1: {{ result()[0].status() }}, error1:
{{ result()[0].error()?.message ?? 'none' }}
</div>
<div>
status2: {{ result()[1].status() }}, data2:
{{ result()[1].data() ?? 'none' }}
</div>
`,
})
class Page {
readonly result = injectQueries(() => ({
queries: [
{
queryKey: key1,
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
retry: false,
},
{
queryKey: key2,
queryFn: () => sleep(10).then(() => 2),
},
],
}))
}
const rendered = await render(Page)
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(
rendered.getByText('status1: error, error1: Some error'),
).toBeInTheDocument()
expect(rendered.getByText('status2: success, data2: 2')).toBeInTheDocument()
})
describe('isRestoring', () => {
it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
const key1 = queryKey()
const key2 = queryKey()
const queryFn1 = vi.fn().mockImplementation(() => sleep(10).then(() => 1))
const queryFn2 = vi.fn().mockImplementation(() => sleep(10).then(() => 2))
TestBed.configureTestingModule({
providers: [provideIsRestoring(signal(true).asReadonly())],
})
@Component({
template: `
<div>
status1: {{ queries()[0].status() }}, fetchStatus1:
{{ queries()[0].fetchStatus() }}
</div>
<div>
status2: {{ queries()[1].status() }}, fetchStatus2:
{{ queries()[1].fetchStatus() }}
</div>
`,
})
class Page {
readonly queries = injectQueries(() => ({
queries: [
{ queryKey: key1, queryFn: queryFn1 },
{ queryKey: key2, queryFn: queryFn2 },
],
}))
}
const rendered = await render(Page)
await vi.advanceTimersByTimeAsync(0)
rendered.fixture.detectChanges()
expect(
rendered.getByText('status1: pending, fetchStatus1: idle'),
).toBeInTheDocument()
expect(
rendered.getByText('status2: pending, fetchStatus2: idle'),
).toBeInTheDocument()
expect(queryFn1).toHaveBeenCalledTimes(0)
expect(queryFn2).toHaveBeenCalledTimes(0)
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(
rendered.getByText('status1: pending, fetchStatus1: idle'),
).toBeInTheDocument()
expect(
rendered.getByText('status2: pending, fetchStatus2: idle'),
).toBeInTheDocument()
expect(queryFn1).toHaveBeenCalledTimes(0)
expect(queryFn2).toHaveBeenCalledTimes(0)
})
})
})

View File

@@ -0,0 +1,357 @@
import { describe, expectTypeOf, it } from 'vitest'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import { injectQuery, queryOptions } from '..'
import type { Signal } from '@angular/core'
import type { CreateQueryOptions, OmitKeyof, QueryFunction } from '..'
describe('injectQuery', () => {
it('should return the correct types', () => {
const key = queryKey()
// unspecified query function should default to unknown
const noQueryFn = injectQuery(() => ({
queryKey: key,
}))
expectTypeOf(noQueryFn.data()).toEqualTypeOf<unknown>()
expectTypeOf(noQueryFn.error()).toEqualTypeOf<Error | null>()
// it should infer the result type from the query function
const fromQueryFn = injectQuery(() => ({
queryKey: key,
queryFn: () => 'test',
}))
expectTypeOf(fromQueryFn.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(fromQueryFn.error()).toEqualTypeOf<Error | null>()
// it should be possible to specify the result type
const withResult = injectQuery<string>(() => ({
queryKey: key,
queryFn: () => 'test',
}))
expectTypeOf(withResult.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(withResult.error()).toEqualTypeOf<Error | null>()
// it should be possible to specify the error type
type CustomErrorType = { message: string }
const withError = injectQuery<string, CustomErrorType>(() => ({
queryKey: key,
queryFn: () => 'test',
}))
expectTypeOf(withError.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(withError.error()).toEqualTypeOf<CustomErrorType | null>()
// it should infer the result type from the configuration
const withResultInfer = injectQuery(() => ({
queryKey: key,
queryFn: () => true,
}))
expectTypeOf(withResultInfer.data()).toEqualTypeOf<boolean | undefined>()
expectTypeOf(withResultInfer.error()).toEqualTypeOf<Error | null>()
// it should be possible to specify a union type as result type
const unionTypeSync = injectQuery(() => ({
queryKey: key,
queryFn: () => (Math.random() > 0.5 ? ('a' as const) : ('b' as const)),
}))
expectTypeOf(unionTypeSync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
const unionTypeAsync = injectQuery<'a' | 'b'>(() => ({
queryKey: key,
queryFn: () => Promise.resolve(Math.random() > 0.5 ? 'a' : 'b'),
}))
expectTypeOf(unionTypeAsync.data()).toEqualTypeOf<'a' | 'b' | undefined>()
// it should error when the query function result does not match with the specified type
// @ts-expect-error
injectQuery<number>(() => ({ queryKey: key, queryFn: () => 'test' }))
// it should infer the result type from a generic query function
/**
*
*/
function queryFn<T = string>(): Promise<T> {
return Promise.resolve({} as T)
}
const fromGenericQueryFn = injectQuery(() => ({
queryKey: key,
queryFn: () => queryFn(),
}))
expectTypeOf(fromGenericQueryFn.data()).toEqualTypeOf<string | undefined>()
expectTypeOf(fromGenericQueryFn.error()).toEqualTypeOf<Error | null>()
type MyData = number
type MyQueryKey = readonly ['my-data', number]
const getMyDataArrayKey: QueryFunction<MyData, MyQueryKey> = ({
queryKey: [, n],
}) => {
return n + 42
}
const fromMyDataArrayKeyQueryFn = injectQuery(() => ({
queryKey: ['my-data', 100] as const,
queryFn: getMyDataArrayKey,
}))
expectTypeOf(fromMyDataArrayKeyQueryFn.data()).toEqualTypeOf<
number | undefined
>()
// it should handle query-functions that return Promise<any>
const fromPromiseAnyQueryFn = injectQuery(() => ({
queryKey: key,
queryFn: () => fetch('return Promise<any>').then((resp) => resp.json()),
}))
expectTypeOf(fromPromiseAnyQueryFn.data()).toEqualTypeOf<any | undefined>()
const getMyDataStringKey: QueryFunction<MyData, ['1']> = (context) => {
expectTypeOf(context.queryKey).toEqualTypeOf<['1']>()
return Number(context.queryKey[0]) + 42
}
const fromGetMyDataStringKeyQueryFn = injectQuery(() => ({
queryKey: ['1'] as ['1'],
queryFn: getMyDataStringKey,
}))
expectTypeOf(fromGetMyDataStringKeyQueryFn.data()).toEqualTypeOf<
number | undefined
>()
// handles wrapped queries with custom fetcher passed as inline queryFn
const createWrappedQuery = <
TQueryKey extends [string, Record<string, unknown>?],
TQueryFnData,
TError,
TData = TQueryFnData,
>(
qk: TQueryKey,
fetcher: (
obj: TQueryKey[1],
token: string,
// return type must be wrapped with TQueryFnReturn
) => Promise<TQueryFnData>,
options?: OmitKeyof<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn' | 'initialData',
'safely'
>,
) =>
injectQuery(() => ({
queryKey: qk,
queryFn: () => fetcher(qk[1], 'token'),
...options,
}))
const fromWrappedQuery = createWrappedQuery([''], () =>
Promise.resolve('1'),
)
expectTypeOf(fromWrappedQuery.data()).toEqualTypeOf<string | undefined>()
// handles wrapped queries with custom fetcher passed directly to createQuery
const createWrappedFuncStyleQuery = <
TQueryKey extends [string, Record<string, unknown>?],
TQueryFnData,
TError,
TData = TQueryFnData,
>(
qk: TQueryKey,
fetcher: () => Promise<TQueryFnData>,
options?: OmitKeyof<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryKey' | 'queryFn' | 'initialData',
'safely'
>,
) => injectQuery(() => ({ queryKey: qk, queryFn: fetcher, ...options }))
const fromWrappedFuncStyleQuery = createWrappedFuncStyleQuery([''], () =>
Promise.resolve(true),
)
expectTypeOf(fromWrappedFuncStyleQuery.data()).toEqualTypeOf<
boolean | undefined
>()
})
describe('initialData', () => {
describe('Config object overload', () => {
it('TData should always be defined when initialData is provided as an object', () => {
const key = queryKey()
const { data } = injectQuery(() => ({
queryKey: key,
queryFn: () => ({ wow: true }),
initialData: { wow: true },
}))
expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean }>>()
})
it('TData should be defined when passed through queryOptions', () => {
const key = queryKey()
const options = () =>
queryOptions({
queryKey: key,
queryFn: () => {
return {
wow: true,
}
},
initialData: {
wow: true,
},
})
const { data } = injectQuery(options)
expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean }>>()
})
it('should be possible to define a different TData than TQueryFnData using select with queryOptions spread into useQuery', () => {
const key = queryKey()
const options = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(1),
})
const query = injectQuery(() => ({
...options,
select: (data) => data > 1,
}))
expectTypeOf(query.data).toEqualTypeOf<Signal<boolean | undefined>>()
})
it('TData should always be defined when initialData is provided as a function which ALWAYS returns the data', () => {
const key = queryKey()
const { data } = injectQuery(() => ({
queryKey: key,
queryFn: () => {
return {
wow: true,
}
},
initialData: () => ({
wow: true,
}),
}))
expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean }>>()
})
it('TData should have undefined in the union when initialData is NOT provided', () => {
const key = queryKey()
const { data } = injectQuery(() => ({
queryKey: key,
queryFn: () => {
return {
wow: true,
}
},
}))
expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean } | undefined>>()
})
it('TData should have undefined in the union when initialData is provided as a function which can return undefined', () => {
const key = queryKey()
const { data } = injectQuery(() => ({
queryKey: key,
queryFn: () => {
return {
wow: true,
}
},
initialData: () => undefined as { wow: boolean } | undefined,
}))
expectTypeOf(data).toEqualTypeOf<Signal<{ wow: boolean } | undefined>>()
})
it('TData should be narrowed after an isSuccess check when initialData is provided as a function which can return undefined', () => {
const key = queryKey()
const query = injectQuery(() => ({
queryKey: key,
queryFn: () => {
return {
wow: true,
}
},
initialData: () => undefined as { wow: boolean } | undefined,
}))
if (query.isSuccess()) {
expectTypeOf(query.data).toEqualTypeOf<Signal<{ wow: boolean }>>()
}
})
})
describe('structuralSharing', () => {
it('should be able to use structuralSharing with unknown types', () => {
const key = queryKey()
// https://github.com/TanStack/query/issues/6525#issuecomment-1938411343
injectQuery(() => ({
queryKey: key,
queryFn: () => 5,
structuralSharing: (oldData, newData) => {
expectTypeOf(oldData).toBeUnknown()
expectTypeOf(newData).toBeUnknown()
return newData
},
}))
})
})
})
describe('Discriminated union return type', () => {
it('data should be possibly undefined by default', () => {
const key = queryKey()
const query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}))
expectTypeOf(query.data).toEqualTypeOf<Signal<string | undefined>>()
})
it('data should be defined when query is success', () => {
const key = queryKey()
const query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}))
if (query.isSuccess()) {
expectTypeOf(query.data).toEqualTypeOf<Signal<string>>()
}
})
it('error should be null when query is success', () => {
const key = queryKey()
const query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}))
if (query.isSuccess()) {
expectTypeOf(query.error).toEqualTypeOf<Signal<null>>()
}
})
it('data should be undefined when query is pending', () => {
const key = queryKey()
const query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}))
if (query.isPending()) {
expectTypeOf(query.data).toEqualTypeOf<Signal<undefined>>()
}
})
it('error should be defined when query is error', () => {
const key = queryKey()
const query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}))
if (query.isError()) {
expectTypeOf(query.error).toEqualTypeOf<Signal<Error>>()
}
})
})
})

View File

@@ -0,0 +1,700 @@
import {
ApplicationRef,
Component,
Injector,
computed,
input,
provideZonelessChangeDetection,
signal,
} from '@angular/core'
import { TestBed } from '@angular/core/testing'
import { HttpClient, provideHttpClient } from '@angular/common/http'
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { render } from '@testing-library/angular'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import { lastValueFrom } from 'rxjs'
import {
QueryCache,
QueryClient,
injectQuery,
provideIsRestoring,
provideTanStackQuery,
} from '..'
import { setSignalInputs } from './test-utils'
describe('injectQuery', () => {
let queryCache: QueryCache
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryCache = new QueryCache()
queryClient = new QueryClient({ queryCache })
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
it('should return pending status initially', () => {
const key = queryKey()
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(10).then(() => 'Some data'),
}))
})
expect(query.status()).toBe('pending')
expect(query.isPending()).toBe(true)
expect(query.isFetching()).toBe(true)
expect(query.isStale()).toBe(true)
expect(query.isFetched()).toBe(false)
})
it('should resolve to success and update signal: injectQuery()', async () => {
const key = queryKey()
@Component({
template: `
<div>status: {{ query.status() }}</div>
<div>data: {{ query.data() ?? 'none' }}</div>
<div>isPending: {{ query.isPending() }}</div>
<div>isFetching: {{ query.isFetching() }}</div>
<div>isFetched: {{ query.isFetched() }}</div>
<div>isSuccess: {{ query.isSuccess() }}</div>
`,
})
class Page {
readonly query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(10).then(() => 'result2'),
}))
}
const rendered = await render(Page)
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('status: success')).toBeInTheDocument()
expect(rendered.getByText('data: result2')).toBeInTheDocument()
expect(rendered.getByText('isPending: false')).toBeInTheDocument()
expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
expect(rendered.getByText('isFetched: true')).toBeInTheDocument()
expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
})
it('should reject and update signal', async () => {
const key = queryKey()
@Component({
template: `
<div>status: {{ query.status() }}</div>
<div>data: {{ query.data() ?? 'none' }}</div>
<div>error: {{ query.error()?.message ?? 'none' }}</div>
<div>isPending: {{ query.isPending() }}</div>
<div>isFetching: {{ query.isFetching() }}</div>
<div>isError: {{ query.isError() }}</div>
<div>failureCount: {{ query.failureCount() }}</div>
<div>failureReason: {{ query.failureReason()?.message ?? 'none' }}</div>
`,
})
class Page {
readonly query = injectQuery(() => ({
retry: false,
queryKey: key,
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
}))
}
const rendered = await render(Page)
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('status: error')).toBeInTheDocument()
expect(rendered.getByText('data: none')).toBeInTheDocument()
expect(rendered.getByText('error: Some error')).toBeInTheDocument()
expect(rendered.getByText('isPending: false')).toBeInTheDocument()
expect(rendered.getByText('isFetching: false')).toBeInTheDocument()
expect(rendered.getByText('isError: true')).toBeInTheDocument()
expect(rendered.getByText('failureCount: 1')).toBeInTheDocument()
expect(rendered.getByText('failureReason: Some error')).toBeInTheDocument()
})
it('should be able to select a part of the data with select', async () => {
const key = queryKey()
@Component({
template: `<div>data: {{ query.data() ?? 'none' }}</div>`,
})
class Page {
readonly query = injectQuery<{ name: string }, Error, string>(() => ({
queryKey: key,
queryFn: () => sleep(10).then(() => ({ name: 'test' })),
select: (data) => data.name,
}))
}
const rendered = await render(Page)
expect(rendered.getByText('data: none')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('data: test')).toBeInTheDocument()
})
it('should show placeholderData until queryFn resolves and then expose real data', async () => {
const key = queryKey()
@Component({
template: `
<div>data: {{ query.data() }}</div>
<div>isPlaceholderData: {{ query.isPlaceholderData() }}</div>
<div>isSuccess: {{ query.isSuccess() }}</div>
`,
})
class Page {
readonly query = injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(10).then(() => 'real-data'),
placeholderData: 'placeholder',
}))
}
const rendered = await render(Page)
expect(rendered.getByText('data: placeholder')).toBeInTheDocument()
expect(rendered.getByText('isPlaceholderData: true')).toBeInTheDocument()
expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('data: real-data')).toBeInTheDocument()
expect(rendered.getByText('isPlaceholderData: false')).toBeInTheDocument()
expect(rendered.getByText('isSuccess: true')).toBeInTheDocument()
})
it('should update query on options contained signal change', async () => {
const key1 = queryKey()
const key2 = queryKey()
const key = signal(key1)
const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key(),
queryFn: spy,
}))
})
await vi.advanceTimersByTimeAsync(0)
expect(spy).toHaveBeenCalledTimes(1)
await vi.advanceTimersByTimeAsync(10)
expect(query.status()).toBe('success')
key.set(key2)
TestBed.tick()
expect(spy).toHaveBeenCalledTimes(2)
// should call queryFn with context containing the new queryKey
expect(spy).toHaveBeenNthCalledWith(2, {
client: queryClient,
meta: undefined,
queryKey: key2,
signal: expect.anything(),
})
})
it('should only run query once enabled signal is set to true', async () => {
const key = queryKey()
const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
const enabled = signal(false)
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key,
queryFn: spy,
enabled: enabled(),
}))
})
expect(spy).not.toHaveBeenCalled()
expect(query.status()).toBe('pending')
enabled.set(true)
await vi.advanceTimersByTimeAsync(10)
expect(spy).toHaveBeenCalledTimes(1)
expect(query.status()).toBe('success')
})
it('should not fetch while the enabled signal is false, and fetch again once it is truthy', async () => {
const key = queryKey()
const spy = vi.fn(() => sleep(10).then(() => 'Some data'))
const filter = signal('a')
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: [...key, filter()],
queryFn: spy,
enabled: !!filter(),
}))
})
await vi.advanceTimersByTimeAsync(10)
expect(spy).toHaveBeenCalledTimes(1)
expect(query.status()).toBe('success')
filter.set('')
await vi.advanceTimersByTimeAsync(10)
expect(spy).toHaveBeenCalledTimes(1)
expect(query.isFetching()).toBe(false)
filter.set('b')
await vi.advanceTimersByTimeAsync(10)
expect(spy).toHaveBeenCalledTimes(2)
})
it('should properly execute dependent queries', async () => {
const key1 = queryKey()
const key2 = queryKey()
const query1 = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key1,
queryFn: () => sleep(10).then(() => 'Some data'),
}))
})
const dependentQueryFn = vi
.fn()
.mockImplementation(() => sleep(1000).then(() => 'Some data'))
const query2 = TestBed.runInInjectionContext(() => {
return injectQuery(
computed(() => ({
queryKey: key2,
queryFn: dependentQueryFn,
enabled: !!query1.data(),
})),
)
})
expect(query1.data()).toStrictEqual(undefined)
expect(query2.fetchStatus()).toStrictEqual('idle')
expect(dependentQueryFn).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(11)
expect(query1.data()).toStrictEqual('Some data')
expect(query2.fetchStatus()).toStrictEqual('fetching')
await vi.advanceTimersByTimeAsync(1002)
expect(query2.fetchStatus()).toStrictEqual('idle')
expect(query2.status()).toStrictEqual('success')
expect(dependentQueryFn).toHaveBeenCalledTimes(1)
expect(dependentQueryFn).toHaveBeenCalledWith(
expect.objectContaining({ queryKey: key2 }),
)
})
it('should use the current value for the queryKey when refetch is called', async () => {
const key = queryKey()
const fetchFn = vi.fn(() => sleep(10).then(() => 'Some data'))
const keySignal = signal('key11')
const query = TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: [...key, keySignal()],
queryFn: fetchFn,
enabled: false,
}))
})
expect(fetchFn).not.toHaveBeenCalled()
void query.refetch()
await vi.advanceTimersByTimeAsync(10)
expect(fetchFn).toHaveBeenCalledTimes(1)
expect(fetchFn).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
queryKey: [...key, 'key11'],
}),
)
keySignal.set('key12')
void query.refetch()
await vi.advanceTimersByTimeAsync(10)
expect(fetchFn).toHaveBeenCalledTimes(2)
expect(fetchFn).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
queryKey: [...key, 'key12'],
}),
)
expect(query.data()).toBe('Some data')
})
it('should keep initialData visible alongside the error when a refetch fails', async () => {
const key = queryKey()
@Component({
template: `
<div>data: {{ query.data() }}</div>
<div>isError: {{ query.isError() }}</div>
`,
})
class Page {
readonly query = injectQuery(() => ({
queryKey: key,
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
initialData: 'initial',
retry: false,
}))
}
const rendered = await render(Page)
expect(rendered.getByText('data: initial')).toBeInTheDocument()
expect(rendered.getByText('isError: false')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(11)
rendered.fixture.detectChanges()
expect(rendered.getByText('data: initial')).toBeInTheDocument()
expect(rendered.getByText('isError: true')).toBeInTheDocument()
})
describe('throwOnError', () => {
it('should evaluate throwOnError when query is expected to throw', async () => {
const key = queryKey()
const boundaryFn = vi.fn()
TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key,
queryFn: () =>
sleep(10).then(() => Promise.reject(new Error('Some error'))),
retry: false,
throwOnError: boundaryFn,
}))
})
await vi.advanceTimersByTimeAsync(11)
expect(boundaryFn).toHaveBeenCalledTimes(1)
expect(boundaryFn).toHaveBeenCalledWith(
Error('Some error'),
expect.objectContaining({
state: expect.objectContaining({ status: 'error' }),
}),
)
})
it('should throw when throwOnError is true', async () => {
const key = queryKey()
TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key,
queryFn: () =>
sleep(0).then(() => Promise.reject(new Error('Some error'))),
throwOnError: true,
}))
})
await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
})
it('should throw when throwOnError function returns true', async () => {
const key = queryKey()
TestBed.runInInjectionContext(() => {
return injectQuery(() => ({
queryKey: key,
queryFn: () =>
sleep(0).then(() => Promise.reject(new Error('Some error'))),
throwOnError: () => true,
}))
})
await expect(vi.runAllTimersAsync()).rejects.toThrow('Some error')
})
})
it('should render with required signal inputs', async () => {
@Component({
selector: 'app-fake',
template: `{{ query.data() }}`,
})
class FakeComponent {
name = input.required<string>()
query = injectQuery(() => ({
queryKey: ['fake', this.name()],
queryFn: () => this.name(),
}))
}
const fixture = TestBed.createComponent(FakeComponent)
setSignalInputs(fixture.componentInstance, {
name: 'signal-input-required-test',
})
fixture.detectChanges()
await vi.advanceTimersByTimeAsync(0)
expect(fixture.componentInstance.query.data()).toEqual(
'signal-input-required-test',
)
})
describe('isRestoring', () => {
it('should not fetch for the duration of the restoring period when isRestoring is true', async () => {
const key = queryKey()
const queryFn = vi
.fn()
.mockImplementation(() => sleep(10).then(() => 'data'))
TestBed.configureTestingModule({
providers: [provideIsRestoring(signal(true).asReadonly())],
})
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn,
})),
)
await vi.advanceTimersByTimeAsync(0)
expect(query.status()).toBe('pending')
expect(query.fetchStatus()).toBe('idle')
expect(query.data()).toBeUndefined()
expect(queryFn).toHaveBeenCalledTimes(0)
await vi.advanceTimersByTimeAsync(10)
expect(query.status()).toBe('pending')
expect(query.fetchStatus()).toBe('idle')
expect(query.data()).toBeUndefined()
expect(queryFn).toHaveBeenCalledTimes(0)
})
})
describe('injection context', () => {
it('should throw NG0203 with descriptive error outside injection context', () => {
const key = queryKey()
expect(() => {
injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}))
}).toThrow(/NG0203(.*?)injectQuery/)
})
it('should be usable outside injection context when passing an injector', () => {
const key = queryKey()
const query = injectQuery(
() => ({
queryKey: key,
queryFn: () => sleep(0).then(() => 'Some data'),
}),
{
injector: TestBed.inject(Injector),
},
)
expect(query.status()).toBe('pending')
})
it('should complete queries before whenStable() resolves', async () => {
const key = queryKey()
const app = TestBed.inject(ApplicationRef)
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(50).then(() => 'test data'),
})),
)
expect(query.status()).toBe('pending')
expect(query.data()).toBeUndefined()
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(60)
await stablePromise
expect(query.status()).toBe('success')
expect(query.data()).toBe('test data')
})
it('should complete HttpClient-based queries before whenStable() resolves', async () => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
})
const app = TestBed.inject(ApplicationRef)
const httpClient = TestBed.inject(HttpClient)
const httpTestingController = TestBed.inject(HttpTestingController)
// Create a query using HttpClient
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () =>
lastValueFrom(httpClient.get<{ message: string }>('/api/test')),
})),
)
// Schedule the HTTP response
setTimeout(() => {
const req = httpTestingController.expectOne('/api/test')
req.flush({ message: 'http test data' })
}, 10)
// Initial state
expect(query.status()).toBe('pending')
// Advance timers and wait for Angular to be "stable"
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(20)
await stablePromise
// Query should be complete after whenStable() thanks to PendingTasks integration
expect(query.status()).toBe('success')
expect(query.data()).toEqual({ message: 'http test data' })
httpTestingController.verify()
})
it('should handle synchronous queryFn with staleTime', async () => {
const app = TestBed.inject(ApplicationRef)
let callCount = 0
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
staleTime: 1000,
queryFn: () => {
callCount++
return `sync-data-${callCount}`
},
})),
)
// Synchronize pending effects
TestBed.tick()
const stablePromise = app.whenStable()
await stablePromise
expect(query.status()).toBe('success')
expect(query.data()).toBe('sync-data-1')
expect(callCount).toBe(1)
await query.refetch()
await Promise.resolve()
await vi.runAllTimersAsync()
await app.whenStable()
expect(query.status()).toBe('success')
expect(query.data()).toBe('sync-data-2')
expect(callCount).toBe(2)
})
it('should handle enabled/disabled transitions with synchronous queryFn', async () => {
const app = TestBed.inject(ApplicationRef)
const enabledSignal = signal(false)
let callCount = 0
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
enabled: enabledSignal(),
queryFn: () => {
callCount++
return `sync-data-${callCount}`
},
})),
)
// Initially disabled
TestBed.tick()
await app.whenStable()
expect(query.status()).toBe('pending')
expect(query.data()).toBeUndefined()
expect(callCount).toBe(0)
// Enable the query
enabledSignal.set(true)
TestBed.tick()
await app.whenStable()
expect(query.status()).toBe('success')
expect(query.data()).toBe('sync-data-1')
expect(callCount).toBe(1)
})
it('should handle query invalidation with synchronous data', async () => {
const app = TestBed.inject(ApplicationRef)
const testKey = queryKey()
let callCount = 0
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: testKey,
queryFn: () => {
callCount++
return `sync-data-${callCount}`
},
})),
)
// Synchronize pending effects
TestBed.tick()
await app.whenStable()
expect(query.status()).toBe('success')
expect(query.data()).toBe('sync-data-1')
expect(callCount).toBe(1)
// Invalidate the query
queryClient.invalidateQueries({ queryKey: testKey })
TestBed.tick()
// Wait for the invalidation to trigger a refetch
await Promise.resolve()
await vi.advanceTimersByTimeAsync(10)
TestBed.tick()
await app.whenStable()
expect(query.status()).toBe('success')
expect(query.data()).toBe('sync-data-2')
expect(callCount).toBe(2)
})
})
})

View File

@@ -0,0 +1,234 @@
import { assertType, describe, expectTypeOf, it } from 'vitest'
import { queryKey } from '@tanstack/query-test-utils'
import { QueryClient } from '@tanstack/query-core'
import {
injectIsMutating,
injectMutation,
injectMutationState,
mutationOptions,
} from '..'
import type {
DefaultError,
MutationFunctionContext,
MutationState,
WithRequired,
} from '@tanstack/query-core'
import type { CreateMutationOptions, CreateMutationResult } from '../types'
describe('mutationOptions', () => {
it('should not allow excess properties', () => {
const key = queryKey()
mutationOptions({
mutationFn: () => Promise.resolve(5),
// @ts-expect-error this is a good error, because onMutates does not exist!
onMutates: 1000,
mutationKey: key,
onSuccess: (data) => {
expectTypeOf(data).toEqualTypeOf<number>()
},
})
})
it('should infer types for callbacks', () => {
const key = queryKey()
mutationOptions({
mutationFn: () => Promise.resolve(5),
mutationKey: key,
onSuccess: (data) => {
expectTypeOf(data).toEqualTypeOf<number>()
},
})
})
it('should infer types for onError callback', () => {
const key = queryKey()
mutationOptions({
mutationFn: () => {
throw new Error('fail')
},
mutationKey: key,
onError: (error) => {
expectTypeOf(error).toEqualTypeOf<DefaultError>()
},
})
})
it('should infer types for variables', () => {
const key = queryKey()
mutationOptions<number, DefaultError, { id: string }>({
mutationFn: (vars) => {
expectTypeOf(vars).toEqualTypeOf<{ id: string }>()
return Promise.resolve(5)
},
mutationKey: key,
})
})
it('should infer result type correctly', () => {
const key = queryKey()
mutationOptions<number, DefaultError, void, { name: string }>({
mutationFn: () => Promise.resolve(5),
mutationKey: key,
onMutate: () => {
return { name: 'onMutateResult' }
},
onSuccess: (_data, _variables, onMutateResult) => {
expectTypeOf(onMutateResult).toEqualTypeOf<{ name: string }>()
},
})
})
it('should infer context type correctly', () => {
const key = queryKey()
mutationOptions<number>({
mutationFn: (_variables, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
return Promise.resolve(5)
},
mutationKey: key,
onMutate: (_variables, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSuccess: (_data, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onError: (_error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSettled: (_data, _error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
})
})
it('should error if mutationFn return type mismatches TData', () => {
assertType(
mutationOptions<number>({
// @ts-expect-error this is a good error, because return type is string, not number
mutationFn: async () => Promise.resolve('wrong return'),
}),
)
})
it('should allow mutationKey to be omitted', () => {
return mutationOptions({
mutationFn: () => Promise.resolve(123),
onSuccess: (data) => {
expectTypeOf(data).toEqualTypeOf<number>()
},
})
})
it('should infer all types when not explicitly provided', () => {
const key = queryKey()
expectTypeOf(
mutationOptions({
mutationFn: (id: string) => Promise.resolve(id.length),
mutationKey: key,
onSuccess: (data) => {
expectTypeOf(data).toEqualTypeOf<number>()
},
}),
).toEqualTypeOf<
WithRequired<
CreateMutationOptions<number, DefaultError, string>,
'mutationKey'
>
>()
expectTypeOf(
mutationOptions({
mutationFn: (id: string) => Promise.resolve(id.length),
onSuccess: (data) => {
expectTypeOf(data).toEqualTypeOf<number>()
},
}),
).toEqualTypeOf<
Omit<CreateMutationOptions<number, DefaultError, string>, 'mutationKey'>
>()
})
it('should infer types when used with injectMutation', () => {
const key = queryKey()
const mutation = injectMutation(() =>
mutationOptions({
mutationKey: key,
mutationFn: () => Promise.resolve('data'),
onSuccess: (data) => {
expectTypeOf(data).toEqualTypeOf<string>()
},
}),
)
expectTypeOf(mutation).toEqualTypeOf<
CreateMutationResult<string, DefaultError, void, unknown>
>()
injectMutation(
// should allow when used with injectMutation without mutationKey
() =>
mutationOptions({
mutationFn: () => Promise.resolve('data'),
onSuccess: (data) => {
expectTypeOf(data).toEqualTypeOf<string>()
},
}),
)
})
it('should infer types when used with injectIsMutating', () => {
const key = queryKey()
const isMutating = injectIsMutating(
mutationOptions({
mutationKey: key,
mutationFn: () => Promise.resolve(5),
}),
)
expectTypeOf(isMutating()).toEqualTypeOf<number>()
injectIsMutating(
// @ts-expect-error filters should have mutationKey
mutationOptions({
mutationFn: () => Promise.resolve(5),
}),
)
})
it('should infer types when used with queryClient.isMutating', () => {
const key = queryKey()
const queryClient = new QueryClient()
const isMutating = queryClient.isMutating(
mutationOptions({
mutationKey: key,
mutationFn: () => Promise.resolve(5),
}),
)
expectTypeOf(isMutating).toEqualTypeOf<number>()
queryClient.isMutating(
// @ts-expect-error filters should have mutationKey
mutationOptions({
mutationFn: () => Promise.resolve(5),
}),
)
})
it('should infer types when used with injectMutationState', () => {
const key = queryKey()
const mutationState = injectMutationState(() => ({
filters: mutationOptions({
mutationKey: key,
mutationFn: () => Promise.resolve(5),
}),
}))
expectTypeOf(mutationState()).toEqualTypeOf<
Array<MutationState<unknown, Error, unknown, unknown>>
>()
injectMutationState({
// @ts-expect-error filters should have mutationKey
filters: mutationOptions({
mutationFn: () => Promise.resolve(5),
}),
})
})
})

View File

@@ -0,0 +1,344 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { provideZonelessChangeDetection } from '@angular/core'
import { TestBed } from '@angular/core/testing'
import { QueryClient } from '@tanstack/query-core'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import {
injectIsMutating,
injectMutation,
injectMutationState,
mutationOptions,
provideTanStackQuery,
} from '..'
import type { CreateMutationOptions } from '../types'
describe('mutationOptions', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryClient = new QueryClient()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
vi.useRealTimers()
})
it('should return the object received as a parameter without any modification (with mutationKey in mutationOptions)', () => {
const key = queryKey()
const object: CreateMutationOptions = {
mutationKey: key,
mutationFn: () => sleep(10).then(() => 5),
} as const
expect(mutationOptions(object)).toBe(object)
})
it('should return the object received as a parameter without any modification (without mutationKey in mutationOptions)', () => {
const object: CreateMutationOptions = {
mutationFn: () => sleep(10).then(() => 5),
} as const
expect(mutationOptions(object)).toBe(object)
})
it('should return the number of fetching mutations when used with injectIsMutating (with mutationKey in mutationOptions)', async () => {
const key = queryKey()
const mutationOpts = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(50).then(() => 'data'),
})
const [mutation, isMutating] = TestBed.runInInjectionContext(() => [
injectMutation(() => mutationOpts),
injectIsMutating(),
])
expect(isMutating()).toBe(0)
mutation.mutate()
expect(isMutating()).toBe(0)
await vi.advanceTimersByTimeAsync(0)
expect(isMutating()).toBe(1)
await vi.advanceTimersByTimeAsync(51)
expect(isMutating()).toBe(0)
})
it('should return the number of fetching mutations when used with injectIsMutating (without mutationKey in mutationOptions)', async () => {
const mutationOpts = mutationOptions({
mutationFn: () => sleep(50).then(() => 'data'),
})
const [mutation, isMutating] = TestBed.runInInjectionContext(() => [
injectMutation(() => mutationOpts),
injectIsMutating(),
])
expect(isMutating()).toBe(0)
mutation.mutate()
expect(isMutating()).toBe(0)
await vi.advanceTimersByTimeAsync(0)
expect(isMutating()).toBe(1)
await vi.advanceTimersByTimeAsync(51)
expect(isMutating()).toBe(0)
})
it('should return the number of fetching mutations when used with injectIsMutating', async () => {
const key = queryKey()
const mutationOpts1 = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(50).then(() => 'data1'),
})
const mutationOpts2 = mutationOptions({
mutationFn: () => sleep(50).then(() => 'data2'),
})
const [mutation1, mutation2, isMutating] = TestBed.runInInjectionContext(
() => [
injectMutation(() => mutationOpts1),
injectMutation(() => mutationOpts2),
injectIsMutating(),
],
)
expect(isMutating()).toBe(0)
mutation1.mutate()
mutation2.mutate()
expect(isMutating()).toBe(0)
await vi.advanceTimersByTimeAsync(0)
expect(isMutating()).toBe(2)
await vi.advanceTimersByTimeAsync(51)
expect(isMutating()).toBe(0)
})
it('should return the number of fetching mutations when used with injectIsMutating (filter mutationOpts1.mutationKey)', async () => {
const key = queryKey()
const mutationOpts1 = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(50).then(() => 'data1'),
})
const mutationOpts2 = mutationOptions({
mutationFn: () => sleep(50).then(() => 'data2'),
})
const [mutation1, mutation2, isMutating] = TestBed.runInInjectionContext(
() => [
injectMutation(() => mutationOpts1),
injectMutation(() => mutationOpts2),
injectIsMutating({ mutationKey: mutationOpts1.mutationKey }),
],
)
expect(isMutating()).toBe(0)
mutation1.mutate()
mutation2.mutate()
expect(isMutating()).toBe(0)
await vi.advanceTimersByTimeAsync(0)
expect(isMutating()).toBe(1)
await vi.advanceTimersByTimeAsync(51)
expect(isMutating()).toBe(0)
})
it('should return the number of fetching mutations when used with queryClient.isMutating (with mutationKey in mutationOptions)', async () => {
const key = queryKey()
const mutationOpts = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(500).then(() => 'data'),
})
const mutation = TestBed.runInInjectionContext(() =>
injectMutation(() => mutationOpts),
)
expect(queryClient.isMutating(mutationOpts)).toBe(0)
mutation.mutate()
expect(queryClient.isMutating(mutationOpts)).toBe(1)
await vi.advanceTimersByTimeAsync(501)
expect(queryClient.isMutating(mutationOpts)).toBe(0)
})
it('should return the number of fetching mutations when used with queryClient.isMutating (without mutationKey in mutationOptions)', async () => {
const mutationOpts = mutationOptions({
mutationFn: () => sleep(500).then(() => 'data'),
})
const mutation = TestBed.runInInjectionContext(() =>
injectMutation(() => mutationOpts),
)
expect(queryClient.isMutating()).toBe(0)
mutation.mutate()
expect(queryClient.isMutating()).toBe(1)
await vi.advanceTimersByTimeAsync(501)
expect(queryClient.isMutating()).toBe(0)
})
it('should return the number of fetching mutations when used with queryClient.isMutating', async () => {
const key = queryKey()
const mutationOpts1 = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(500).then(() => 'data1'),
})
const mutationOpts2 = mutationOptions({
mutationFn: () => sleep(500).then(() => 'data2'),
})
const [mutation1, mutation2] = TestBed.runInInjectionContext(() => [
injectMutation(() => mutationOpts1),
injectMutation(() => mutationOpts2),
])
expect(queryClient.isMutating()).toBe(0)
mutation1.mutate()
mutation2.mutate()
expect(queryClient.isMutating()).toBe(2)
await vi.advanceTimersByTimeAsync(501)
expect(queryClient.isMutating()).toBe(0)
})
it('should return the number of fetching mutations when used with queryClient.isMutating (filter mutationOpt1.mutationKey)', async () => {
const key = queryKey()
const mutationOpts1 = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(500).then(() => 'data1'),
})
const mutationOpts2 = mutationOptions({
mutationFn: () => sleep(500).then(() => 'data2'),
})
const [mutation1, mutation2] = TestBed.runInInjectionContext(() => [
injectMutation(() => mutationOpts1),
injectMutation(() => mutationOpts2),
])
expect(
queryClient.isMutating({ mutationKey: mutationOpts1.mutationKey }),
).toBe(0)
mutation1.mutate()
mutation2.mutate()
expect(
queryClient.isMutating({ mutationKey: mutationOpts1.mutationKey }),
).toBe(1)
await vi.advanceTimersByTimeAsync(501)
expect(
queryClient.isMutating({ mutationKey: mutationOpts1.mutationKey }),
).toBe(0)
})
it('should return the number of fetching mutations when used with injectMutationState (with mutationKey in mutationOptions)', async () => {
const key = queryKey()
const mutationOpts = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(10).then(() => 'data'),
})
const [mutation, mutationState] = TestBed.runInInjectionContext(() => [
injectMutation(() => mutationOpts),
injectMutationState(() => ({
filters: { mutationKey: mutationOpts.mutationKey, status: 'success' },
})),
])
expect(mutationState().length).toBe(0)
mutation.mutate()
await vi.advanceTimersByTimeAsync(11)
expect(mutationState().length).toBe(1)
expect(mutationState()[0]?.data).toBe('data')
})
it('should return the number of fetching mutations when used with injectMutationState (without mutationKey in mutationOptions)', async () => {
const mutationOpts = mutationOptions({
mutationFn: () => sleep(10).then(() => 'data'),
})
const [mutation, mutationState] = TestBed.runInInjectionContext(() => [
injectMutation(() => mutationOpts),
injectMutationState(() => ({
filters: { status: 'success' },
})),
])
expect(mutationState().length).toBe(0)
mutation.mutate()
await vi.advanceTimersByTimeAsync(11)
expect(mutationState().length).toBe(1)
expect(mutationState()[0]?.data).toBe('data')
})
it('should return the number of fetching mutations when used with injectMutationState', async () => {
const key = queryKey()
const mutationOpts1 = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(10).then(() => 'data1'),
})
const mutationOpts2 = mutationOptions({
mutationFn: () => sleep(10).then(() => 'data2'),
})
const [mutation1, mutation2, mutationState] = TestBed.runInInjectionContext(
() => [
injectMutation(() => mutationOpts1),
injectMutation(() => mutationOpts2),
injectMutationState(() => ({
filters: { status: 'success' },
})),
],
)
expect(mutationState().length).toBe(0)
mutation1.mutate()
mutation2.mutate()
await vi.advanceTimersByTimeAsync(11)
expect(mutationState().length).toBe(2)
expect(mutationState()[0]?.data).toBe('data1')
expect(mutationState()[1]?.data).toBe('data2')
})
it('should return the number of fetching mutations when used with injectMutationState (filter mutationOpt1.mutationKey)', async () => {
const key = queryKey()
const mutationOpts1 = mutationOptions({
mutationKey: key,
mutationFn: () => sleep(10).then(() => 'data1'),
})
const mutationOpts2 = mutationOptions({
mutationFn: () => sleep(10).then(() => 'data2'),
})
const [mutation1, mutation2, mutationState] = TestBed.runInInjectionContext(
() => [
injectMutation(() => mutationOpts1),
injectMutation(() => mutationOpts2),
injectMutationState(() => ({
filters: {
mutationKey: mutationOpts1.mutationKey,
status: 'success',
},
})),
],
)
expect(mutationState().length).toBe(0)
mutation1.mutate()
mutation2.mutate()
await vi.advanceTimersByTimeAsync(11)
expect(mutationState().length).toBe(1)
expect(mutationState()[0]?.data).toBe('data1')
})
})

View File

@@ -0,0 +1,644 @@
import {
ApplicationRef,
Component,
provideZonelessChangeDetection,
} from '@angular/core'
import { TestBed } from '@angular/core/testing'
import { HttpClient, provideHttpClient } from '@angular/common/http'
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { queryKey, sleep } from '@tanstack/query-test-utils'
import { lastValueFrom } from 'rxjs'
import {
QueryClient,
injectMutation,
injectQuery,
onlineManager,
provideTanStackQuery,
} from '..'
describe('PendingTasks Integration', () => {
let queryClient: QueryClient
beforeEach(() => {
vi.useFakeTimers()
queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
mutations: {
retry: false,
},
},
})
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
})
afterEach(() => {
onlineManager.setOnline(true)
queryClient.clear()
vi.useRealTimers()
})
describe('Synchronous Resolution', () => {
it('should handle synchronous queryFn with whenStable()', async () => {
const app = TestBed.inject(ApplicationRef)
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => 'instant-data', // Resolves synchronously
})),
)
// Should start as pending even with synchronous data
expect(query.status()).toBe('pending')
expect(query.data()).toBeUndefined()
const stablePromise = app.whenStable()
// Flush microtasks to allow TanStack Query's scheduled notifications to process
await Promise.resolve()
await vi.advanceTimersByTimeAsync(10)
await stablePromise
// Should work correctly even though queryFn was synchronous
expect(query.status()).toBe('success')
expect(query.data()).toBe('instant-data')
})
it('should handle synchronous error with whenStable()', async () => {
const app = TestBed.inject(ApplicationRef)
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => {
throw new Error('instant-error')
}, // Throws synchronously
})),
)
const stablePromise = app.whenStable()
// Flush microtasks to allow TanStack Query's scheduled notifications to process
await Promise.resolve()
await vi.advanceTimersByTimeAsync(10)
await stablePromise
expect(query.status()).toBe('error')
expect(query.error()).toEqual(new Error('instant-error'))
})
it('should handle synchronous mutationFn with whenStable()', async () => {
const app = TestBed.inject(ApplicationRef)
let mutationFnCalled = false
const mutation = TestBed.runInInjectionContext(() =>
injectMutation(() => ({
mutationFn: async (data: string) => {
mutationFnCalled = true
await Promise.resolve()
return `processed: ${data}`
},
})),
)
mutation.mutate('test')
TestBed.tick()
const stablePromise = app.whenStable()
await Promise.resolve()
await vi.advanceTimersByTimeAsync(10)
await stablePromise
expect(mutationFnCalled).toBe(true)
expect(mutation.isSuccess()).toBe(true)
expect(mutation.data()).toBe('processed: test')
})
it('should handle synchronous mutation error with whenStable()', async () => {
const app = TestBed.inject(ApplicationRef)
const mutation = TestBed.runInInjectionContext(() =>
injectMutation(() => ({
mutationFn: async () => {
await Promise.resolve()
throw new Error('sync-mutation-error')
},
})),
)
mutation.mutate()
TestBed.tick()
const stablePromise = app.whenStable()
await Promise.resolve()
await vi.advanceTimersByTimeAsync(10)
await stablePromise
expect(mutation.isError()).toBe(true)
expect(mutation.error()).toEqual(new Error('sync-mutation-error'))
})
})
describe('Race Conditions', () => {
it('should handle query that completes during initial subscription', async () => {
const key = queryKey()
const app = TestBed.inject(ApplicationRef)
let resolveQuery: (value: string) => void
const queryPromise = new Promise<string>((resolve) => {
resolveQuery = resolve
})
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => queryPromise,
})),
)
// Resolve immediately to create potential race condition
resolveQuery!('race-data')
const stablePromise = app.whenStable()
await Promise.resolve()
await vi.advanceTimersByTimeAsync(10)
await stablePromise
expect(query.status()).toBe('success')
expect(query.data()).toBe('race-data')
})
it('should handle rapid refetches without task leaks', async () => {
const app = TestBed.inject(ApplicationRef)
let callCount = 0
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: async () => {
callCount++
await sleep(10)
return `data-${callCount}`
},
})),
)
// Trigger multiple rapid refetches
query.refetch()
query.refetch()
query.refetch()
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(20)
await stablePromise
expect(query.status()).toBe('success')
expect(query.data()).toMatch(/^data-\d+$/)
})
it('should keep PendingTasks active while query retry is paused offline', async () => {
const app = TestBed.inject(ApplicationRef)
let attempt = 0
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
retry: 1,
retryDelay: 50, // Longer delay to ensure we can go offline before retry
queryFn: async () => {
attempt++
if (attempt === 1) {
throw new Error('offline-fail')
}
await sleep(10)
return 'final-data'
},
})),
)
// Allow the initial attempt to start and fail
await vi.advanceTimersByTimeAsync(0)
await Promise.resolve()
// Wait for the first attempt to complete and start retry delay
await vi.advanceTimersByTimeAsync(10)
await Promise.resolve()
expect(query.status()).toBe('pending')
expect(query.fetchStatus()).toBe('fetching')
// Simulate the app going offline during retry delay
onlineManager.setOnline(false)
// Advance past the retry delay to trigger the pause
await vi.advanceTimersByTimeAsync(50)
await Promise.resolve()
expect(query.fetchStatus()).toBe('paused')
const stablePromise = app.whenStable()
let stableResolved = false
void stablePromise.then(() => {
stableResolved = true
})
await Promise.resolve()
// PendingTasks should continue blocking stability while the fetch is paused
expect(stableResolved).toBe(false)
expect(query.status()).toBe('pending')
// Bring the app back online so the retry can continue
onlineManager.setOnline(true)
// Give time for the retry to resume and complete
await vi.advanceTimersByTimeAsync(20)
await Promise.resolve()
await stablePromise
expect(stableResolved).toBe(true)
expect(query.status()).toBe('success')
expect(query.data()).toBe('final-data')
})
})
describe('Component Destruction', () => {
@Component({
template: '',
})
class TestComponent {
query = injectQuery(() => ({
queryKey: ['component-query'],
queryFn: () => sleep(100).then(() => 'component-data'),
}))
mutation = injectMutation(() => ({
mutationFn: (data: string) =>
sleep(100).then(() => `processed: ${data}`),
}))
}
it('should cleanup pending tasks when component with active query is destroyed', async () => {
const app = TestBed.inject(ApplicationRef)
const fixture = TestBed.createComponent(TestComponent)
// Start the query
expect(fixture.componentInstance.query.status()).toBe('pending')
// Destroy component while query is running
fixture.destroy()
// Angular should become stable even though component was destroyed
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(150)
await expect(stablePromise).resolves.toEqual(undefined)
})
it('should cleanup pending tasks when component with active mutation is destroyed', async () => {
const app = TestBed.inject(ApplicationRef)
const fixture = TestBed.createComponent(TestComponent)
fixture.componentInstance.mutation.mutate('test')
// Destroy component while mutation is running
fixture.destroy()
// Angular should become stable even though component was destroyed
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(150)
await expect(stablePromise).resolves.toEqual(undefined)
})
})
describe('Concurrent Operations', () => {
it('should handle multiple queries running simultaneously', async () => {
const key1 = queryKey()
const key2 = queryKey()
const key3 = queryKey()
const app = TestBed.inject(ApplicationRef)
const query1 = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key1,
queryFn: () => sleep(30).then(() => 'data-1'),
})),
)
const query2 = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key2,
queryFn: () => sleep(50).then(() => 'data-2'),
})),
)
const query3 = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key3,
queryFn: () => 'instant-data', // Synchronous
})),
)
// All queries should start
expect(query1.status()).toBe('pending')
expect(query2.status()).toBe('pending')
expect(query3.status()).toBe('pending')
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(60)
await stablePromise
// All queries should be complete
expect(query1.status()).toBe('success')
expect(query1.data()).toBe('data-1')
expect(query2.status()).toBe('success')
expect(query2.data()).toBe('data-2')
expect(query3.status()).toBe('success')
expect(query3.data()).toBe('instant-data')
})
it('should handle multiple mutations running simultaneously', async () => {
const app = TestBed.inject(ApplicationRef)
const mutation1 = TestBed.runInInjectionContext(() =>
injectMutation(() => ({
mutationFn: (data: string) =>
sleep(30).then(() => `processed-1: ${data}`),
})),
)
const mutation2 = TestBed.runInInjectionContext(() =>
injectMutation(() => ({
mutationFn: (data: string) =>
sleep(50).then(() => `processed-2: ${data}`),
})),
)
const mutation3 = TestBed.runInInjectionContext(() =>
injectMutation(() => ({
mutationFn: async (data: string) => {
await Promise.resolve()
return `processed-3: ${data}`
},
})),
)
// Start all mutations
mutation1.mutate('test1')
mutation2.mutate('test2')
mutation3.mutate('test3')
TestBed.tick()
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(60)
await stablePromise
// All mutations should be complete
expect(mutation1.isSuccess()).toBe(true)
expect(mutation1.data()).toBe('processed-1: test1')
expect(mutation2.isSuccess()).toBe(true)
expect(mutation2.data()).toBe('processed-2: test2')
expect(mutation3.isSuccess()).toBe(true)
expect(mutation3.data()).toBe('processed-3: test3')
})
it('should handle mixed queries and mutations', async () => {
const app = TestBed.inject(ApplicationRef)
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(40).then(() => 'query-data'),
})),
)
const mutation = TestBed.runInInjectionContext(() =>
injectMutation(() => ({
mutationFn: (data: string) =>
sleep(60).then(() => `mutation: ${data}`),
})),
)
// Start both operations
mutation.mutate('test')
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(70)
await stablePromise
// Both should be complete
expect(query.status()).toBe('success')
expect(query.data()).toBe('query-data')
expect(mutation.isSuccess()).toBe(true)
expect(mutation.data()).toBe('mutation: test')
})
})
describe('HttpClient Integration', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
})
})
it('should handle multiple HttpClient requests with lastValueFrom', async () => {
const app = TestBed.inject(ApplicationRef)
const httpClient = TestBed.inject(HttpClient)
const httpTestingController = TestBed.inject(HttpTestingController)
const key1 = queryKey()
const key2 = queryKey()
const query1 = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key1,
queryFn: () =>
lastValueFrom(httpClient.get<{ id: number }>('/api/1')),
})),
)
const query2 = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key2,
queryFn: () =>
lastValueFrom(httpClient.get<{ id: number }>('/api/2')),
})),
)
// Schedule HTTP responses
setTimeout(() => {
const req1 = httpTestingController.expectOne('/api/1')
req1.flush({ id: 1 })
const req2 = httpTestingController.expectOne('/api/2')
req2.flush({ id: 2 })
}, 10)
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(20)
await stablePromise
expect(query1.status()).toBe('success')
expect(query1.data()).toEqual({ id: 1 })
expect(query2.status()).toBe('success')
expect(query2.data()).toEqual({ id: 2 })
httpTestingController.verify()
})
it('should handle HttpClient request cancellation', async () => {
const app = TestBed.inject(ApplicationRef)
const httpClient = TestBed.inject(HttpClient)
const httpTestingController = TestBed.inject(HttpTestingController)
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () =>
lastValueFrom(httpClient.get<{ data: string }>('/api/cancel')),
})),
)
// Cancel the request before it completes
setTimeout(() => {
const req = httpTestingController.expectOne('/api/cancel')
req.error(new ProgressEvent('error'), {
status: 0,
statusText: 'Unknown Error',
})
}, 10)
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(20)
await stablePromise
expect(query.status()).toBe('error')
httpTestingController.verify()
})
})
describe('Edge Cases', () => {
it('should handle query cancellation mid-flight', async () => {
const key = queryKey()
const app = TestBed.inject(ApplicationRef)
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
queryFn: () => sleep(100).then(() => 'data'),
})),
)
// Cancel the query after a short delay
setTimeout(() => {
queryClient.cancelQueries({ queryKey: key })
}, 20)
// Advance to the cancellation point
await vi.advanceTimersByTimeAsync(20)
TestBed.tick()
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(130)
await stablePromise
// Cancellation should restore the pre-fetch state
expect(query.status()).toBe('pending')
expect(query.fetchStatus()).toBe('idle')
})
it('should handle query retry and pending task tracking', async () => {
const app = TestBed.inject(ApplicationRef)
let attemptCount = 0
const key = queryKey()
const query = TestBed.runInInjectionContext(() =>
injectQuery(() => ({
queryKey: key,
retry: 2,
retryDelay: 10,
queryFn: async () => {
attemptCount++
if (attemptCount <= 2) {
throw new Error(`Attempt ${attemptCount} failed`)
}
return 'success-data'
},
})),
)
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(50)
await stablePromise
expect(query.status()).toBe('success')
expect(query.data()).toBe('success-data')
expect(attemptCount).toBe(3) // Initial + 2 retries
})
it('should handle mutation with optimistic updates', async () => {
const app = TestBed.inject(ApplicationRef)
const testQueryKey = queryKey()
queryClient.setQueryData(testQueryKey, 'initial-data')
const mutation = TestBed.runInInjectionContext(() =>
injectMutation(() => ({
mutationFn: (newData: string) => sleep(50).then(() => newData),
onMutate: async (newData) => {
// Optimistic update
const previousData = queryClient.getQueryData(testQueryKey)
queryClient.setQueryData(testQueryKey, newData)
return { previousData }
},
onError: (_err, _newData, context) => {
// Rollback on error
if (context?.previousData) {
queryClient.setQueryData(testQueryKey, context.previousData)
}
},
})),
)
mutation.mutate('optimistic-data')
await Promise.resolve()
// Data should be optimistically updated immediately
expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic-data')
const stablePromise = app.whenStable()
await vi.advanceTimersByTimeAsync(60)
await stablePromise
expect(mutation.isSuccess()).toBe(true)
expect(mutation.data()).toBe('optimistic-data')
expect(queryClient.getQueryData(testQueryKey)).toBe('optimistic-data')
})
})
})

View File

@@ -0,0 +1,38 @@
import { TestBed } from '@angular/core/testing'
import { describe, expect, it } from 'vitest'
import { InjectionToken, provideZonelessChangeDetection } from '@angular/core'
import { QueryClient } from '@tanstack/query-core'
import { provideQueryClient } from '../providers'
describe('provideQueryClient', () => {
it('should provide a QueryClient instance directly', () => {
const queryClient = new QueryClient()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideQueryClient(queryClient),
],
})
const providedQueryClient = TestBed.inject(QueryClient)
expect(providedQueryClient).toBe(queryClient)
})
it('should provide a QueryClient instance using an InjectionToken', () => {
const queryClient = new QueryClient()
const CUSTOM_QUERY_CLIENT = new InjectionToken<QueryClient>('', {
factory: () => queryClient,
})
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideQueryClient(CUSTOM_QUERY_CLIENT),
],
})
const providedQueryClient = TestBed.inject(QueryClient)
expect(providedQueryClient).toBe(queryClient)
})
})

View File

@@ -0,0 +1,38 @@
import { TestBed } from '@angular/core/testing'
import { describe, expect, it } from 'vitest'
import { InjectionToken, provideZonelessChangeDetection } from '@angular/core'
import { QueryClient } from '@tanstack/query-core'
import { provideTanStackQuery } from '../providers'
describe('provideTanStackQuery', () => {
it('should provide a QueryClient instance directly', () => {
const queryClient = new QueryClient()
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(queryClient),
],
})
const providedQueryClient = TestBed.inject(QueryClient)
expect(providedQueryClient).toBe(queryClient)
})
it('should provide a QueryClient instance using an InjectionToken', () => {
const queryClient = new QueryClient()
const CUSTOM_QUERY_CLIENT = new InjectionToken<QueryClient>('', {
factory: () => queryClient,
})
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(CUSTOM_QUERY_CLIENT),
],
})
const providedQueryClient = TestBed.inject(QueryClient)
expect(providedQueryClient).toBe(queryClient)
})
})

View File

@@ -0,0 +1,250 @@
import { assertType, describe, expectTypeOf, it } from 'vitest'
import { queryKey } from '@tanstack/query-test-utils'
import {
QueryClient,
dataTagSymbol,
injectQuery,
queryOptions,
skipToken,
} from '..'
import type { Signal } from '@angular/core'
// Regression test for exported queryOptions inference under declaration emit.
// TypeScript should be able to name the return type without expanding the
// internal data tag symbols into the consumer's .d.ts output.
export const exportedQueryOptions = queryOptions({
queryKey: ['invalid'],
})
describe('queryOptions', () => {
it('should not allow excess properties', () => {
expectTypeOf(queryOptions).parameter(0).not.toHaveProperty('stallTime')
})
it('should infer types for callbacks', () => {
const key = queryKey()
queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
staleTime: 1000,
select: (data) => {
expectTypeOf(data).toEqualTypeOf<number>()
},
})
})
it('should allow undefined response in initialData', () => {
const key = queryKey()
const options = (id: string | null) =>
queryOptions({
queryKey: [...key, id],
queryFn: () =>
Promise.resolve({
id: '1',
title: 'Do Laundry',
}),
initialData: () =>
!id
? undefined
: {
id,
title: 'Initial Data',
},
})
expectTypeOf(options(null).initialData).returns.toEqualTypeOf<
{ id: string; title: string } | undefined
>()
})
})
it('should work when passed to injectQuery', () => {
const key = queryKey()
const options = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
})
const { data } = injectQuery(() => options)
expectTypeOf(data).toEqualTypeOf<Signal<number | undefined>>()
})
it('should work when passed to fetchQuery', () => {
const key = queryKey()
const options = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
})
// grandfathered direct test
// eslint-disable-next-line no-restricted-syntax
const data = new QueryClient().fetchQuery(options)
assertType<Promise<number>>(data)
})
it('should work when passed to query', () => {
const options = queryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve(5),
})
const data = new QueryClient().query(options)
assertType<Promise<number>>(data)
})
it('should work when passed to query with select', () => {
const options = queryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve(5),
select: (data) => data.toString(),
})
const data = new QueryClient().query(options)
assertType<Promise<string>>(data)
})
it('should work when passed to query with enabled: false', () => {
const options = queryOptions({
queryKey: ['key'],
queryFn: () => Promise.resolve(5),
enabled: false,
})
const data = new QueryClient().query(options)
assertType<Promise<number>>(data)
})
it('should work when passed to query with skipToken', () => {
const options = queryOptions({
queryKey: ['key'],
queryFn: skipToken,
})
const data = new QueryClient().query(options)
assertType<Promise<unknown>>(data)
})
it('should tag the queryKey with the result type of the QueryFn', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
})
assertType<number>(tagged[dataTagSymbol])
})
it('should tag the queryKey even if no promise is returned', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
queryFn: () => 5,
})
assertType<number>(tagged[dataTagSymbol])
})
it('should tag the queryKey with unknown if there is no queryFn', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
})
assertType<unknown>(tagged[dataTagSymbol])
})
it('should tag the queryKey with the result type of the QueryFn if select is used', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
select: (data) => data.toString(),
})
assertType<number>(tagged[dataTagSymbol])
})
it('should return the proper type when passed to getQueryData', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
})
const queryClient = new QueryClient()
const data = queryClient.getQueryData(tagged)
expectTypeOf(data).toEqualTypeOf<number | undefined>()
})
it('should return the proper type when passed to getQueryState', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
})
const queryClient = new QueryClient()
const state = queryClient.getQueryState(tagged)
expectTypeOf(state?.data).toEqualTypeOf<number | undefined>()
})
it('should properly type updaterFn when passed to setQueryData', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
})
const queryClient = new QueryClient()
const data = queryClient.setQueryData(tagged, (prev) => {
expectTypeOf(prev).toEqualTypeOf<number | undefined>()
return prev
})
expectTypeOf(data).toEqualTypeOf<number | undefined>()
})
it('should properly type value when passed to setQueryData', () => {
const key = queryKey()
const { queryKey: tagged } = queryOptions({
queryKey: key,
queryFn: () => Promise.resolve(5),
})
const queryClient = new QueryClient()
// @ts-expect-error value should be a number
queryClient.setQueryData(tagged, '5')
// @ts-expect-error value should be a number
queryClient.setQueryData(tagged, () => '5')
const data = queryClient.setQueryData(tagged, 5)
expectTypeOf(data).toEqualTypeOf<number | undefined>()
})
it('should infer even if there is a conditional skipToken', () => {
const key = queryKey()
const options = queryOptions({
queryKey: key,
queryFn: Math.random() > 0.5 ? skipToken : () => Promise.resolve(5),
})
const queryClient = new QueryClient()
const data = queryClient.getQueryData(options.queryKey)
expectTypeOf(data).toEqualTypeOf<number | undefined>()
})
it('should infer to unknown if we disable a query with just a skipToken', () => {
const key = queryKey()
const options = queryOptions({
queryKey: key,
queryFn: skipToken,
})
const queryClient = new QueryClient()
const data = queryClient.getQueryData(options.queryKey)
expectTypeOf(data).toEqualTypeOf<unknown>()
})

View File

@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest'
import { queryOptions } from '../query-options'
import type { CreateQueryOptions } from '../types'
describe('queryOptions', () => {
it('should return the object received as a parameter without any modification.', () => {
const object: CreateQueryOptions = {
queryKey: ['key'],
queryFn: () => Promise.resolve(5),
} as const
expect(queryOptions(object)).toBe(object)
})
})

View File

@@ -0,0 +1,27 @@
import { isSignal, signal } from '@angular/core'
import { describe, expect, it } from 'vitest'
import { signalProxy } from '../signal-proxy'
describe('signalProxy', () => {
const inputSignal = signal({ fn: () => 'bar', baz: 'qux' })
const proxy = signalProxy(inputSignal)
it('should have computed fields', () => {
expect(proxy.baz()).toEqual('qux')
expect(isSignal(proxy.baz)).toBe(true)
})
it('should pass through functions as-is', () => {
expect(proxy.fn()).toEqual('bar')
expect(isSignal(proxy.fn)).toBe(false)
})
it('should support "in" operator', () => {
expect('baz' in proxy).toBe(true)
expect('foo' in proxy).toBe(false)
})
it('should support "Object.keys"', () => {
expect(Object.keys(proxy)).toEqual(['fn', 'baz'])
})
})

View File

@@ -0,0 +1,77 @@
import { isSignal, untracked } from '@angular/core'
import { SIGNAL, signalSetFn } from '@angular/core/primitives/signals'
import { expect } from 'vitest'
import type { InputSignal, Signal } from '@angular/core'
import type { ComponentFixture } from '@angular/core/testing'
// Evaluate all signals on an object and return the result
function evaluateSignals<T extends Record<string, any>>(
obj: T,
): { [K in keyof T]: ReturnType<T[K]> } {
const result: Partial<{ [K in keyof T]: ReturnType<T[K]> }> = {}
untracked(() => {
for (const key in obj) {
if (
Object.prototype.hasOwnProperty.call(obj, key) &&
// Only evaluate signals, not normal functions
isSignal(obj[key])
) {
const func = obj[key]
result[key] = func()
}
}
})
return result as { [K in keyof T]: ReturnType<T[K]> }
}
export const expectSignals = <T extends Record<string, any>>(
obj: T,
expected: Partial<{
[K in keyof T]: T[K] extends Signal<any> ? ReturnType<T[K]> : never
}>,
): void => {
expect(evaluateSignals(obj)).toMatchObject(expected)
}
type ToSignalInputUpdatableMap<T> = {
[K in keyof T as T[K] extends InputSignal<any>
? K
: never]: T[K] extends InputSignal<infer Value> ? Value : never
}
function componentHasSignalInputProperty<TProperty extends string>(
component: object,
property: TProperty,
): component is { [key in TProperty]: InputSignal<unknown> } {
return (
component.hasOwnProperty(property) && (component as any)[property][SIGNAL]
)
}
/**
* Set required signal input value to component fixture
* @see https://github.com/angular/angular/issues/54013
*/
export function setSignalInputs<T extends NonNullable<unknown>>(
component: T,
inputs: ToSignalInputUpdatableMap<T>,
) {
for (const inputKey in inputs) {
if (componentHasSignalInputProperty(component, inputKey)) {
signalSetFn(component[inputKey][SIGNAL], inputs[inputKey])
}
}
}
export function setFixtureSignalInputs<T extends NonNullable<unknown>>(
componentFixture: ComponentFixture<T>,
inputs: ToSignalInputUpdatableMap<T>,
options: { detectChanges: boolean } = { detectChanges: true },
) {
setSignalInputs(componentFixture.componentInstance, inputs)
if (options.detectChanges) {
componentFixture.detectChanges()
}
}

View File

@@ -0,0 +1,674 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { QueryClient } from '@tanstack/query-core'
import { TestBed } from '@angular/core/testing'
import {
ENVIRONMENT_INITIALIZER,
EnvironmentInjector,
InjectionToken,
PLATFORM_ID,
createEnvironmentInjector,
isDevMode,
provideZonelessChangeDetection,
signal,
} from '@angular/core'
import { provideTanStackQuery } from '../providers'
import { withDevtools } from '../devtools'
import type {
DevtoolsButtonPosition,
DevtoolsErrorType,
DevtoolsPosition,
Theme,
} from '@tanstack/query-devtools'
import type { DevtoolsOptions } from '../devtools'
const mockDevtoolsInstance = {
mount: vi.fn(),
unmount: vi.fn(),
setClient: vi.fn(),
setPosition: vi.fn(),
setErrorTypes: vi.fn(),
setButtonPosition: vi.fn(),
setInitialIsOpen: vi.fn(),
setTheme: vi.fn(),
}
function MockTanstackQueryDevtools() {
return mockDevtoolsInstance
}
const mockTanstackQueryDevtools = vi.fn(MockTanstackQueryDevtools)
vi.mock('@tanstack/query-devtools', () => ({
TanstackQueryDevtools: mockTanstackQueryDevtools,
}))
vi.mock('@angular/core', async () => {
const actual = await vi.importActual('@angular/core')
return {
...actual,
isDevMode: vi.fn(),
}
})
const mockIsDevMode = vi.mocked(isDevMode)
describe('withDevtools feature', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.useFakeTimers()
})
afterEach(() => {
vi.restoreAllMocks()
TestBed.resetTestingModule()
vi.useRealTimers()
})
it.each([
{
description: 'should load devtools in development mode',
isDevMode: true,
expectedCalled: true,
},
{
description: 'should not load devtools in production mode',
isDevMode: false,
expectedCalled: false,
},
{
description: `should load devtools in development mode when 'loadDevtools' is set to 'auto'`,
isDevMode: true,
loadDevtools: 'auto',
expectedCalled: true,
},
{
description: `should not load devtools in production mode when 'loadDevtools' is set to 'auto'`,
isDevMode: false,
loadDevtools: 'auto',
expectedCalled: false,
},
{
description:
"should load devtools in development mode when 'loadDevtools' is set to true",
isDevMode: true,
loadDevtools: true,
expectedCalled: true,
},
{
description:
"should load devtools in production mode when 'loadDevtools' is set to true",
isDevMode: false,
loadDevtools: true,
expectedCalled: true,
},
{
description:
"should not load devtools in development mode when 'loadDevtools' is set to false",
isDevMode: true,
loadDevtools: false,
expectedCalled: false,
},
{
description:
"should not load devtools in production mode when 'loadDevtools' is set to false",
isDevMode: false,
loadDevtools: false,
expectedCalled: false,
},
])(
'$description',
async ({ isDevMode: isDevModeValue, loadDevtools, expectedCalled }) => {
mockIsDevMode.mockReturnValue(isDevModeValue)
const providers = [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
loadDevtools !== undefined
? withDevtools(
() =>
({
loadDevtools,
}) as DevtoolsOptions,
)
: withDevtools(),
),
]
TestBed.configureTestingModule({
providers,
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
TestBed.tick()
await vi.dynamicImportSettled()
TestBed.tick()
await vi.dynamicImportSettled()
expect(mockTanstackQueryDevtools).toHaveBeenCalledTimes(
expectedCalled ? 1 : 0,
)
expect(mockDevtoolsInstance.mount).toHaveBeenCalledTimes(
expectedCalled ? 1 : 0,
)
},
)
it("should throw 'No QueryClient found' when 'loadDevtools' is 'true' and no 'QueryClient' is provided", async () => {
const consoleErrorSpy = vi
.spyOn(console, 'error')
.mockImplementation(() => undefined)
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
withDevtools(() => ({
loadDevtools: true,
})).ɵproviders,
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
TestBed.tick()
await vi.dynamicImportSettled()
expect(mockTanstackQueryDevtools).not.toHaveBeenCalled()
expect(consoleErrorSpy).toHaveBeenCalledWith(
'Install @tanstack/query-devtools or reinstall without --omit=optional.',
expect.objectContaining({ message: 'No QueryClient found' }),
)
consoleErrorSpy.mockRestore()
})
it('should not continue loading devtools after injector is destroyed', async () => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
// Destroys injector
TestBed.resetTestingModule()
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
expect(mockTanstackQueryDevtools).not.toHaveBeenCalled()
})
it('should not create devtools again when already provided', async () => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
expect(mockTanstackQueryDevtools).toHaveBeenCalledTimes(1)
const injector = TestBed.inject(EnvironmentInjector)
createEnvironmentInjector(
[
withDevtools(() => ({
loadDevtools: true,
})).ɵproviders,
],
injector,
)
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
expect(mockTanstackQueryDevtools).toHaveBeenCalledTimes(1)
})
it('should not load devtools if platform is not browser', async () => {
TestBed.configureTestingModule({
providers: [
{
provide: PLATFORM_ID,
useValue: 'server',
},
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.runAllTimersAsync()
expect(mockTanstackQueryDevtools).not.toHaveBeenCalled()
})
it('should update error types', async () => {
const errorTypes = signal([] as Array<DevtoolsErrorType>)
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
errorTypes: errorTypes(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
TestBed.tick()
expect(mockDevtoolsInstance.setErrorTypes).toHaveBeenCalledTimes(0)
const newErrorTypes = [
{
name: '',
initializer: () => new Error(),
},
]
errorTypes.set(newErrorTypes)
TestBed.tick()
expect(mockDevtoolsInstance.setErrorTypes).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.setErrorTypes).toHaveBeenCalledWith(
newErrorTypes,
)
})
it('should update client', async () => {
const client = signal(new QueryClient())
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
client: client(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
TestBed.tick()
expect(mockDevtoolsInstance.setClient).toHaveBeenCalledTimes(0)
const newClient = new QueryClient()
client.set(newClient)
TestBed.tick()
expect(mockDevtoolsInstance.setClient).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.setClient).toHaveBeenCalledWith(newClient)
})
it('should update position', async () => {
const position = signal<DevtoolsPosition>('top')
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
position: position(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
TestBed.tick()
expect(mockDevtoolsInstance.setPosition).toHaveBeenCalledTimes(0)
position.set('left')
TestBed.tick()
expect(mockDevtoolsInstance.setPosition).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.setPosition).toHaveBeenCalledWith('left')
})
it('should update button position', async () => {
const buttonPosition = signal<DevtoolsButtonPosition>('bottom-left')
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
buttonPosition: buttonPosition(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
TestBed.tick()
expect(mockDevtoolsInstance.setButtonPosition).toHaveBeenCalledTimes(0)
buttonPosition.set('bottom-right')
TestBed.tick()
expect(mockDevtoolsInstance.setButtonPosition).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.setButtonPosition).toHaveBeenCalledWith(
'bottom-right',
)
})
it('should update initialIsOpen', async () => {
const initialIsOpen = signal(false)
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
initialIsOpen: initialIsOpen(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
TestBed.tick()
expect(mockDevtoolsInstance.setInitialIsOpen).toHaveBeenCalledTimes(0)
initialIsOpen.set(true)
TestBed.tick()
expect(mockDevtoolsInstance.setInitialIsOpen).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.setInitialIsOpen).toHaveBeenCalledWith(true)
})
it('should update theme', async () => {
const theme = signal<Theme>('system')
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
theme: theme(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
TestBed.tick()
expect(mockDevtoolsInstance.setTheme).toHaveBeenCalledTimes(0)
theme.set('dark')
TestBed.tick()
expect(mockDevtoolsInstance.setTheme).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.setTheme).toHaveBeenCalledWith('dark')
})
it('should destroy devtools', async () => {
const loadDevtools = signal(true)
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: loadDevtools(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
await vi.dynamicImportSettled()
expect(mockDevtoolsInstance.mount).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.unmount).toHaveBeenCalledTimes(0)
loadDevtools.set(false)
TestBed.tick()
expect(mockDevtoolsInstance.unmount).toHaveBeenCalledTimes(1)
})
it('should unmount devtools when injector is destroyed', async () => {
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: true,
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
TestBed.tick()
await vi.dynamicImportSettled()
expect(mockTanstackQueryDevtools).toHaveBeenCalled()
expect(mockDevtoolsInstance.mount).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.unmount).toHaveBeenCalledTimes(0)
// Destroy the injector
TestBed.resetTestingModule()
expect(mockDevtoolsInstance.unmount).toHaveBeenCalledTimes(1)
})
it('should remount devtools when toggled from false to true', async () => {
const loadDevtools = signal(false)
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(() => ({
loadDevtools: loadDevtools(),
})),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
expect(mockTanstackQueryDevtools).not.toHaveBeenCalled()
expect(mockDevtoolsInstance.mount).not.toHaveBeenCalled()
loadDevtools.set(true)
TestBed.tick()
await vi.dynamicImportSettled()
expect(mockTanstackQueryDevtools).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.mount).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.unmount).not.toHaveBeenCalled()
loadDevtools.set(false)
TestBed.tick()
expect(mockDevtoolsInstance.unmount).toHaveBeenCalledTimes(1)
expect(mockDevtoolsInstance.mount).toHaveBeenCalledTimes(1)
loadDevtools.set(true)
TestBed.tick()
await vi.dynamicImportSettled()
// Should remount (mount called twice now)
expect(mockDevtoolsInstance.mount).toHaveBeenCalledTimes(2)
expect(mockDevtoolsInstance.unmount).toHaveBeenCalledTimes(1)
})
describe('deps parameter', () => {
it('should inject dependencies and pass them to withDevtoolsFn in correct order', async () => {
const mockService1 = { value: 'service1' }
const mockService2 = { value: 'service2' }
const mockService1Token = new InjectionToken('MockService1')
const mockService2Token = new InjectionToken('MockService2')
const withDevtoolsFn = vi.fn().mockReturnValue({ loadDevtools: true })
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
{
provide: mockService1Token,
useValue: mockService1,
},
{
provide: mockService2Token,
useValue: mockService2,
},
provideTanStackQuery(
new QueryClient(),
withDevtools(withDevtoolsFn, {
deps: [mockService1Token, mockService2Token],
}),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
expect(withDevtoolsFn).toHaveBeenCalledWith(mockService1, mockService2)
})
it('should work with empty deps array', async () => {
const withDevtoolsFn = vi.fn().mockReturnValue({ loadDevtools: true })
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
provideTanStackQuery(
new QueryClient(),
withDevtools(withDevtoolsFn, {
deps: [],
}),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
expect(withDevtoolsFn).toHaveBeenCalledWith()
})
it('should reactively update when injected services change', async () => {
class ReactiveService {
enabled = signal(false)
position = signal<DevtoolsPosition>('bottom')
}
const withDevtoolsFn = (service: ReactiveService) => ({
loadDevtools: service.enabled(),
position: service.position(),
})
TestBed.configureTestingModule({
providers: [
provideZonelessChangeDetection(),
ReactiveService,
provideTanStackQuery(
new QueryClient(),
withDevtools(withDevtoolsFn, {
deps: [ReactiveService],
}),
),
],
})
TestBed.inject(ENVIRONMENT_INITIALIZER)
await vi.advanceTimersByTimeAsync(0)
const service = TestBed.inject(ReactiveService)
expect(mockTanstackQueryDevtools).not.toHaveBeenCalled()
service.enabled.set(true)
TestBed.tick()
await vi.dynamicImportSettled()
expect(mockTanstackQueryDevtools).toHaveBeenCalledTimes(1)
expect(mockTanstackQueryDevtools).toHaveBeenCalledWith(
expect.objectContaining({
position: 'bottom',
}),
)
service.position.set('top')
TestBed.tick()
expect(mockDevtoolsInstance.setPosition).toHaveBeenCalledWith('top')
})
})
})

View File

@@ -0,0 +1,175 @@
import {
NgZone,
VERSION,
computed,
effect,
inject,
signal,
untracked,
} from '@angular/core'
import {
QueryClient,
notifyManager,
shouldThrowError,
} from '@tanstack/query-core'
import { signalProxy } from './signal-proxy'
import { injectIsRestoring } from './inject-is-restoring'
import { PENDING_TASKS } from './pending-tasks-compat'
import type { PendingTaskRef } from './pending-tasks-compat'
import type {
QueryKey,
QueryObserver,
QueryObserverResult,
} from '@tanstack/query-core'
import type { CreateBaseQueryOptions } from './types'
/**
* Base implementation for `injectQuery` and `injectInfiniteQuery`.
* @param optionsFn
* @param Observer
*/
export function createBaseQuery<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
optionsFn: () => CreateBaseQueryOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>,
Observer: typeof QueryObserver,
) {
const ngZone = inject(NgZone)
const pendingTasks = inject(PENDING_TASKS)
const queryClient = inject(QueryClient)
const isRestoring = injectIsRestoring()
/**
* Signal that has the default options from query client applied
* computed() is used so signals can be inserted into the options
* making it reactive. Wrapping options in a function ensures embedded expressions
* are preserved and can keep being applied after signal changes
*/
const defaultedOptionsSignal = computed(() => {
const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
defaultedOptions._optimisticResults = isRestoring()
? 'isRestoring'
: 'optimistic'
return defaultedOptions
})
const observerSignal = (() => {
let instance: QueryObserver<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
> | null = null
return computed(() => {
return (instance ||= new Observer(queryClient, defaultedOptionsSignal()))
})
})()
const optimisticResultSignal = computed(() =>
observerSignal().getOptimisticResult(defaultedOptionsSignal()),
)
const resultFromSubscriberSignal = signal<QueryObserverResult<
TData,
TError
> | null>(null)
effect(
(onCleanup) => {
const observer = observerSignal()
const defaultedOptions = defaultedOptionsSignal()
untracked(() => {
observer.setOptions(defaultedOptions)
})
onCleanup(() => {
ngZone.run(() => resultFromSubscriberSignal.set(null))
})
},
{
// Set allowSignalWrites to support Angular < v19
// Set to undefined to avoid warning on newer versions
allowSignalWrites: VERSION.major < '19' || undefined,
},
)
effect((onCleanup) => {
// observer.trackResult is not used as this optimization is not needed for Angular
const observer = observerSignal()
let pendingTaskRef: PendingTaskRef | null = null
const unsubscribe = isRestoring()
? () => undefined
: untracked(() =>
ngZone.runOutsideAngular(() => {
return observer.subscribe(
notifyManager.batchCalls((state) => {
ngZone.run(() => {
if (state.fetchStatus === 'fetching' && !pendingTaskRef) {
pendingTaskRef = pendingTasks.add()
}
if (state.fetchStatus === 'idle' && pendingTaskRef) {
pendingTaskRef()
pendingTaskRef = null
}
if (
state.isError &&
!state.isFetching &&
shouldThrowError(observer.options.throwOnError, [
state.error,
observer.getCurrentQuery(),
])
) {
ngZone.onError.emit(state.error)
throw state.error
}
resultFromSubscriberSignal.set(state)
})
}),
)
}),
)
onCleanup(() => {
if (pendingTaskRef) {
pendingTaskRef()
pendingTaskRef = null
}
unsubscribe()
})
})
return signalProxy(
computed(() => {
const subscriberResult = resultFromSubscriberSignal()
const optimisticResult = optimisticResultSignal()
const result = subscriberResult ?? optimisticResult
// Wrap methods to ensure observer has latest options before execution
const observer = observerSignal()
const originalRefetch = result.refetch
return {
...result,
refetch: ((...args: Parameters<typeof originalRefetch>) => {
observer.setOptions(defaultedOptionsSignal())
return originalRefetch(...args)
}) as typeof originalRefetch,
}
}),
)
}

View File

@@ -0,0 +1,8 @@
export type {
InjectDevtoolsPanel,
DevtoolsPanelOptions,
InjectDevtoolsPanelOptions,
DevtoolsPanelRef,
} from './types'
export { injectDevtoolsPanel } from './inject-devtools-panel'

View File

@@ -0,0 +1,110 @@
import {
DestroyRef,
Injector,
PLATFORM_ID,
assertInInjectionContext,
computed,
effect,
inject,
runInInjectionContext,
untracked,
} from '@angular/core'
import { QueryClient, onlineManager } from '@tanstack/query-core'
import { isPlatformBrowser } from '@angular/common'
import type { TanstackQueryDevtoolsPanel } from '@tanstack/query-devtools'
import type {
DevtoolsPanelOptions,
InjectDevtoolsPanel,
InjectDevtoolsPanelOptions,
} from './types'
/**
* Inject a TanStack Query devtools panel and render it in the DOM.
*
* Devtools panel allows programmatic control over the devtools, for example if you want to render
* the devtools as part of your own devtools.
*
* Consider `withDevtools` instead if you don't need this.
* @param injectDevtoolsPanelFn - A function that returns devtools panel options.
* @param options - Additional configuration
* @returns DevtoolsPanelRef
* @see https://tanstack.com/query/v5/docs/framework/angular/devtools
*/
export const injectDevtoolsPanel: InjectDevtoolsPanel = (
injectDevtoolsPanelFn: () => DevtoolsPanelOptions,
options?: InjectDevtoolsPanelOptions,
) => {
!options?.injector && assertInInjectionContext(injectDevtoolsPanel)
const currentInjector = options?.injector ?? inject(Injector)
return runInInjectionContext(currentInjector, () => {
const destroyRef = inject(DestroyRef)
const isBrowser = isPlatformBrowser(inject(PLATFORM_ID))
const injectedClient = inject(QueryClient, { optional: true })
const queryOptions = computed(injectDevtoolsPanelFn)
let devtools: TanstackQueryDevtoolsPanel | null = null
const destroy = () => {
devtools?.unmount()
devtools = null
}
if (!isBrowser)
return {
destroy,
}
effect(() => {
const {
client = injectedClient,
errorTypes = [],
styleNonce,
shadowDOMTarget,
onClose,
hostElement,
} = queryOptions()
untracked(() => {
if (!client) throw new Error('No QueryClient found')
if (!devtools && hostElement) {
import('@tanstack/query-devtools')
.then((queryDevtools) => {
devtools = new queryDevtools.TanstackQueryDevtoolsPanel({
client,
queryFlavor: 'Angular Query',
version: '5',
buttonPosition: 'bottom-left',
position: 'bottom',
initialIsOpen: true,
errorTypes,
styleNonce,
shadowDOMTarget,
onClose,
onlineManager,
})
devtools.mount(hostElement.nativeElement)
})
.catch((error) => {
console.error(
'Install @tanstack/query-devtools or reinstall without --omit=optional.',
error,
)
})
} else if (devtools && hostElement) {
devtools.setClient(client)
devtools.setErrorTypes(errorTypes)
onClose && devtools.setOnClose(onClose)
} else if (devtools && !hostElement) {
destroy()
}
})
})
destroyRef.onDestroy(destroy)
return {
destroy,
}
})
}

View File

@@ -0,0 +1 @@
export * from '..'

View File

@@ -0,0 +1,7 @@
import { noop } from '@tanstack/query-core'
import type { InjectDevtoolsPanel } from './types'
// Stub which replaces `injectDevtoolsPanel` in production builds
export const injectDevtoolsPanel: InjectDevtoolsPanel = () => ({
destroy: noop,
})

View File

@@ -0,0 +1,57 @@
import type { DevtoolsErrorType } from '@tanstack/query-devtools'
import type { ElementRef, Injector } from '@angular/core'
import type { QueryClient } from '@tanstack/query-core'
export interface InjectDevtoolsPanelOptions {
/**
* The `Injector` in which to create the devtools panel.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* A devtools panel, which can be manually destroyed.
*/
export interface DevtoolsPanelRef {
/**
* Destroy the panel, removing it from the DOM and stops listening to signal changes.
*/
destroy: () => void
}
export interface DevtoolsPanelOptions {
/**
* Custom instance of QueryClient
*/
client?: QueryClient
/**
* Use this so you can define custom errors that can be shown in the devtools.
*/
errorTypes?: Array<DevtoolsErrorType>
/**
* Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
*/
styleNonce?: string
/**
* Use this so you can attach the devtool's styles to specific element in the DOM.
*/
shadowDOMTarget?: ShadowRoot
/**
* Callback function that is called when the devtools panel is closed
*/
onClose?: () => void
/**
* Element where to render the devtools panel. When set to undefined or null, the devtools panel will not be created, or destroyed if existing.
* If changed from undefined to a ElementRef, the devtools panel will be created.
*/
hostElement?: ElementRef
}
export type InjectDevtoolsPanel = (
injectDevtoolsPanelFn: () => DevtoolsPanelOptions,
options?: InjectDevtoolsPanelOptions,
) => DevtoolsPanelRef

View File

@@ -0,0 +1,8 @@
export type {
DevtoolsOptions,
WithDevtools,
WithDevtoolsFn,
WithDevtoolsOptions,
} from './types'
export { withDevtools } from './with-devtools'

View File

@@ -0,0 +1 @@
export * from '..'

View File

@@ -0,0 +1,7 @@
import type { WithDevtools } from './types'
// Stub which replaces `withDevtools` in production builds
export const withDevtools: WithDevtools = () => ({
ɵkind: 'Devtools',
ɵproviders: [],
})

View File

@@ -0,0 +1,113 @@
import type { QueryClient } from '@tanstack/query-core'
import type {
DevtoolsButtonPosition,
DevtoolsErrorType,
DevtoolsPosition,
Theme,
} from '@tanstack/query-devtools'
import type { DevtoolsFeature } from '../providers'
/**
* Options for configuring withDevtools.
*/
export interface WithDevtoolsOptions {
/**
* An array of dependencies to be injected and passed to the `withDevtoolsFn` function.
*
* **Example**
* ```ts
* export const appConfig: ApplicationConfig = {
* providers: [
* provideTanStackQuery(
* new QueryClient(),
* withDevtools(
* (devToolsOptionsManager: DevtoolsOptionsManager) => ({
* loadDevtools: devToolsOptionsManager.loadDevtools(),
* }),
* {
* deps: [DevtoolsOptionsManager],
* },
* ),
* ),
* ],
* }
* ```
*/
deps?: Array<any>
}
/**
* Options for configuring the TanStack Query devtools.
*/
export interface DevtoolsOptions {
/**
* Set this true if you want the devtools to default to being open
*/
initialIsOpen?: boolean
/**
* The position of the TanStack logo to open and close the devtools panel.
* `top-left` | `top-right` | `bottom-left` | `bottom-right` | `relative`
* Defaults to `bottom-right`.
*/
buttonPosition?: DevtoolsButtonPosition
/**
* The position of the Angular Query devtools panel.
* `top` | `bottom` | `left` | `right`
* Defaults to `bottom`.
*/
position?: DevtoolsPosition
/**
* Custom instance of QueryClient
*/
client?: QueryClient
/**
* Use this so you can define custom errors that can be shown in the devtools.
*/
errorTypes?: Array<DevtoolsErrorType>
/**
* Use this to pass a nonce to the style tag that is added to the document head. This is useful if you are using a Content Security Policy (CSP) nonce to allow inline styles.
*/
styleNonce?: string
/**
* Use this so you can attach the devtool's styles to a specific element in the DOM.
*/
shadowDOMTarget?: ShadowRoot
/**
* Set this to true to hide disabled queries from the devtools panel.
*/
hideDisabledQueries?: boolean
/**
* Set this to 'light', 'dark', or 'system' to change the theme of the devtools panel.
* Defaults to 'system'.
*/
theme?: Theme
/**
* Whether the developer tools should load.
* - `auto`- (Default) Lazily loads devtools when in development mode. Skips loading in production mode.
* - `true`- Always load the devtools, regardless of the environment.
* - `false`- Never load the devtools, regardless of the environment.
*
* You can use `true` and `false` to override loading developer tools from an environment file.
* For example, a test environment might run in production mode but you may want to load developer tools.
*
* Additionally, you can use a signal in the callback to dynamically load the devtools based on a condition. For example,
* a signal created from a RxJS observable that listens for a keyboard shortcut.
*
* **Example**
* ```ts
* withDevtools(() => ({
* initialIsOpen: true,
* loadDevtools: inject(ExampleService).loadDevtools()
* }))
* ```
*/
loadDevtools?: 'auto' | boolean
}
export type WithDevtoolsFn = (...deps: Array<any>) => DevtoolsOptions
export type WithDevtools = (
withDevtoolsFn?: WithDevtoolsFn,
options?: WithDevtoolsOptions,
) => DevtoolsFeature

View File

@@ -0,0 +1,182 @@
import { isPlatformBrowser } from '@angular/common'
import {
DestroyRef,
ENVIRONMENT_INITIALIZER,
InjectionToken,
Injector,
PLATFORM_ID,
computed,
effect,
inject,
isDevMode,
} from '@angular/core'
import { QueryClient, noop, onlineManager } from '@tanstack/query-core'
import { queryFeature } from '../providers'
import type { Signal } from '@angular/core'
import type {
DevtoolsOptions,
WithDevtools,
WithDevtoolsFn,
WithDevtoolsOptions,
} from './types'
import type { TanstackQueryDevtools } from '@tanstack/query-devtools'
/**
* Internal token used to prevent double providing of devtools in child injectors
*/
const DEVTOOLS_PROVIDED = new InjectionToken('', {
factory: () => ({
isProvided: false,
}),
})
/**
* Internal token for providing devtools options
*/
const DEVTOOLS_OPTIONS_SIGNAL = new InjectionToken<Signal<DevtoolsOptions>>('')
/**
* Enables developer tools in Angular development builds.
*
* **Example**
*
* ```ts
* export const appConfig: ApplicationConfig = {
* providers: [
* provideTanStackQuery(new QueryClient(), withDevtools())
* ]
* }
* ```
* The devtools will be rendered in `<body>`.
*
* If you need more control over when devtools are loaded, you can use the `loadDevtools` option.
*
* If you need more control over where devtools are rendered, consider `injectDevtoolsPanel`. This allows rendering devtools inside your own devtools for example.
* @param withDevtoolsFn - A function that returns `DevtoolsOptions`.
* @param options - Additional options for configuring `withDevtools`.
* @returns A set of providers for use with `provideTanStackQuery`.
* @see {@link provideTanStackQuery}
* @see {@link DevtoolsOptions}
*/
export const withDevtools: WithDevtools = (
withDevtoolsFn?: WithDevtoolsFn,
options: WithDevtoolsOptions = {},
) =>
queryFeature('Devtools', [
{
provide: DEVTOOLS_OPTIONS_SIGNAL,
useFactory: (...deps: Array<any>) =>
computed(() => withDevtoolsFn?.(...deps) ?? {}),
deps: options.deps || [],
},
{
// Do not use provideEnvironmentInitializer while Angular < v19 is supported
provide: ENVIRONMENT_INITIALIZER,
multi: true,
useFactory: () => {
const devtoolsProvided = inject(DEVTOOLS_PROVIDED)
if (
!isPlatformBrowser(inject(PLATFORM_ID)) ||
devtoolsProvided.isProvided
)
return noop
devtoolsProvided.isProvided = true
let injectorIsDestroyed = false
inject(DestroyRef).onDestroy(() => (injectorIsDestroyed = true))
return () => {
const injectedClient = inject(QueryClient, {
optional: true,
})
const destroyRef = inject(DestroyRef)
const devtoolsOptions = inject(DEVTOOLS_OPTIONS_SIGNAL)
const injector = inject(Injector)
let devtools: TanstackQueryDevtools | null = null
let el: HTMLElement | null = null
const shouldLoadToolsSignal = computed(() => {
const { loadDevtools } = devtoolsOptions()
return typeof loadDevtools === 'boolean'
? loadDevtools
: isDevMode()
})
const getResolvedQueryClient = () => {
const client = devtoolsOptions().client ?? injectedClient
if (!client) {
throw new Error('No QueryClient found')
}
return client
}
const destroyDevtools = () => {
devtools?.unmount()
el?.remove()
devtools = null
}
effect(
() => {
const shouldLoadTools = shouldLoadToolsSignal()
const {
client,
position,
errorTypes,
buttonPosition,
initialIsOpen,
theme,
} = devtoolsOptions()
if (!shouldLoadTools) {
// Destroy or do nothing
devtools && destroyDevtools()
return
}
if (devtools) {
// Update existing devtools config
client && devtools.setClient(client)
position && devtools.setPosition(position)
errorTypes && devtools.setErrorTypes(errorTypes)
buttonPosition && devtools.setButtonPosition(buttonPosition)
typeof initialIsOpen === 'boolean' &&
devtools.setInitialIsOpen(initialIsOpen)
theme && devtools.setTheme(theme)
return
}
// Create devtools
import('@tanstack/query-devtools')
.then((queryDevtools) => {
// As this code runs async, the injector could have been destroyed
if (injectorIsDestroyed) return
devtools = new queryDevtools.TanstackQueryDevtools({
...devtoolsOptions(),
client: getResolvedQueryClient(),
queryFlavor: 'Angular Query',
version: '5',
onlineManager,
})
el = document.body.appendChild(document.createElement('div'))
el.classList.add('tsqd-parent-container')
devtools.mount(el)
destroyRef.onDestroy(destroyDevtools)
})
.catch((error) => {
console.error(
'Install @tanstack/query-devtools or reinstall without --omit=optional.',
error,
)
})
},
{ injector },
)
}
},
},
])

View File

@@ -0,0 +1,60 @@
/* istanbul ignore file */
// Re-export core
export * from '@tanstack/query-core'
export * from './types'
export type {
DefinedInitialDataOptions,
UndefinedInitialDataOptions,
UnusedSkipTokenOptions,
} from './query-options'
export { queryOptions } from './query-options'
export type { CreateMutationOptions } from './types'
export { mutationOptions } from './mutation-options'
export type {
DefinedInitialDataInfiniteOptions,
UndefinedInitialDataInfiniteOptions,
UnusedSkipTokenInfiniteOptions,
} from './infinite-query-options'
export { infiniteQueryOptions } from './infinite-query-options'
export type { InjectInfiniteQueryOptions } from './inject-infinite-query'
export { injectInfiniteQuery } from './inject-infinite-query'
export type { InjectIsFetchingOptions } from './inject-is-fetching'
export { injectIsFetching } from './inject-is-fetching'
export type { InjectIsMutatingOptions } from './inject-is-mutating'
export { injectIsMutating } from './inject-is-mutating'
export { injectIsRestoring, provideIsRestoring } from './inject-is-restoring'
export type { InjectMutationOptions } from './inject-mutation'
export { injectMutation } from './inject-mutation'
export type { InjectMutationStateOptions } from './inject-mutation-state'
export { injectMutationState } from './inject-mutation-state'
export type { QueriesOptions, QueriesResults } from './inject-queries'
export type { InjectQueryOptions } from './inject-query'
export { injectQuery } from './inject-query'
export { injectQueryClient } from './inject-query-client'
export type {
DevtoolsFeature,
PersistQueryClientFeature,
QueryFeature,
QueryFeatures,
} from './providers'
export {
provideAngularQuery,
provideQueryClient,
provideTanStackQuery,
queryFeature,
} from './providers'

View File

@@ -0,0 +1,354 @@
import type {
DefaultError,
InfiniteData,
InitialDataFunction,
NonUndefinedGuard,
OmitKeyof,
QueryKey,
QueryKeyWithDataTag,
SkipToken,
} from '@tanstack/query-core'
import type { CreateInfiniteQueryOptions } from './types'
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set — `data`
* may be `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export type UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> = CreateInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?:
| undefined
| NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>
| InitialDataFunction<
NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>
>
}
/**
* The options accepted by the `infiniteQueryOptions` overload selected when no `initialData` is set and
* `queryFn` is not `skipToken` — same as {@link UndefinedInitialDataInfiniteOptions}, but `queryFn` may not be
* `skipToken`.
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export type UnusedSkipTokenInfiniteOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> = OmitKeyof<
CreateInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
'queryFn'
> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<
CreateInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>['queryFn'],
SkipToken | undefined
>
}
/**
* The options accepted by the `infiniteQueryOptions` overload selected when `initialData` is set — `data` is
* never `undefined` (unless a `select` changes `TData` to include `undefined`).
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData<TQueryFnData>`,
* the shape of all fetched pages plus their page params.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export type DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> = CreateInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData:
| NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>
| (() => NonUndefinedGuard<InfiniteData<TQueryFnData, TPageParam>>)
| undefined
}
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to
* `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as
* `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options
* for.
*
* This overload is selected when `initialData` is set.
*
* @see {@link injectInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link DefinedInitialDataInfiniteOptions} to use — everything you can pass to
* `injectInfiniteQuery`, with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link injectInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* ```angular-ts
* import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query-experimental'
*
* export const projectsOptions = infiniteQueryOptions({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* initialData: { pages: [], pageParams: [] },
* })
*
* @Component({
* selector: 'projects',
* template: `
* <!-- `projectsQuery.data()` is never `undefined`, thanks to `initialData` — even if a
* refetch fails, so the list stays visible alongside the error. -->
* <ul>
* @for (page of projectsQuery.data().pages; track $index) {
* @for (project of page.projects; track project.id) {
* <li>{{ project.name }}</li>
* }
* }
* </ul>
* `,
* })
* export class Projects {
* readonly projectsQuery = injectInfiniteQuery(() => projectsOptions)
* }
* ```
*/
export function infiniteQueryOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
): DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> &
QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to
* `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as
* `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options
* for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link injectInfiniteQuery} for examples that fetch further pages, from a button click or
* automatically as the user scrolls.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```angular-ts
* import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query-experimental'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* @Component({
* selector: 'comments',
* template: `
* @if (commentsQuery.isPending()) {
* Loading...
* } @else if (commentsQuery.isError()) {
* <span>Error: {{ commentsQuery.error()?.message }}</span>
* } @else {
* <ul>
* @for (page of commentsQuery.data().pages; track $index) {
* @for (comment of page.comments; track comment.id) {
* <li>{{ comment.text }}</li>
* }
* }
* </ul>
* }
* `,
* })
* export class Comments {
* readonly postId = signal('1')
* readonly commentsQuery = injectInfiniteQuery(() => commentsOptions(this.postId()))
* }
* ```
*
* @see {@link injectInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UnusedSkipTokenInfiniteOptions} to use — everything you can pass to
* `injectInfiniteQuery`.
*/
export function infiniteQueryOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UnusedSkipTokenInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
): UnusedSkipTokenInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> &
QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>
/**
* You can generally pass everything to `infiniteQueryOptions` that you can also pass to
* `injectInfiniteQuery`. These options can be shared across functions and imperative APIs such as
* `queryClient.fetchInfiniteQuery`. `options.queryKey` is required and is the query key to generate options
* for.
*
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks See {@link injectInfiniteQuery} for examples that fetch further pages (from a button click or
* automatically as the user scrolls) and that use `skipToken` to disable the query until `postId` is set.
*
* @example
* A parameterized factory, so the same options object can be reused per `postId`:
* ```angular-ts
* import { infiniteQueryOptions, injectInfiniteQuery } from '@tanstack/angular-query-experimental'
*
* export const commentsOptions = (postId: string) =>
* infiniteQueryOptions({
* queryKey: ['post', postId, 'comments'],
* queryFn: ({ pageParam }) => fetchComments(postId, pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* })
*
* @Component({
* selector: 'comments',
* template: `
* @if (commentsQuery.isPending()) {
* Loading...
* } @else if (commentsQuery.isError()) {
* <span>Error: {{ commentsQuery.error()?.message }}</span>
* } @else {
* <ul>
* @for (page of commentsQuery.data().pages; track $index) {
* @for (comment of page.comments; track comment.id) {
* <li>{{ comment.text }}</li>
* }
* }
* </ul>
* }
* `,
* })
* export class Comments {
* readonly postId = signal('1')
* readonly commentsQuery = injectInfiniteQuery(() => commentsOptions(this.postId()))
* }
* ```
*
* @see {@link injectInfiniteQuery} to run an infinite query with these options.
* @param options - The {@link UndefinedInitialDataInfiniteOptions} to use — everything you can pass to
* `injectInfiniteQuery`.
*/
export function infiniteQueryOptions<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
options: UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
): UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
> &
QueryKeyWithDataTag<TQueryKey, InfiniteData<TQueryFnData>, TError>
export function infiniteQueryOptions(options: unknown) {
return options
}

View File

@@ -0,0 +1,296 @@
import { InfiniteQueryObserver } from '@tanstack/query-core'
import {
Injector,
assertInInjectionContext,
inject,
runInInjectionContext,
} from '@angular/core'
import { createBaseQuery } from './create-base-query'
import type {
DefaultError,
InfiniteData,
QueryKey,
QueryObserver,
} from '@tanstack/query-core'
import type {
CreateInfiniteQueryOptions,
CreateInfiniteQueryResult,
DefinedCreateInfiniteQueryResult,
} from './types'
import type {
DefinedInitialDataInfiniteOptions,
UndefinedInitialDataInfiniteOptions,
} from './infinite-query-options'
export interface InjectInfiniteQueryOptions {
/**
* The `Injector` in which to create the infinite query.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* The options for `injectInfiniteQuery` are identical to `injectQuery`, with the addition of
* `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`. Infinite queries can
* additively "load more" data onto an existing set of data, or "infinite scroll".
*
* This overload is selected when `initialData` is set on the options returned by `injectInfiniteQueryFn`,
* so the resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).
*
* @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
* refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
* actions, or add conditions like `hasNextPage() && !isFetching()`.
* @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs
* like `queryClient.fetchInfiniteQuery`.
* @param injectInfiniteQueryFn - A function returning the {@link DefinedInitialDataInfiniteOptions} to use —
* everything you can pass to `injectInfiniteQuery`, with `initialData` set. Similar to `computed` from
* Angular, this function runs in the reactive context, so signals read inside it drive the query.
* @param options - Additional configuration.
* @returns The same signals as `injectQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
* `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data().pages` and
* `data().pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
* `InfiniteData<TQueryFnData>` shape.
*
* @example
* ```angular-ts
* @Component({
* selector: 'projects',
* template: `
* <!-- `projectsQuery.data()` is never `undefined`, thanks to `initialData` — even if a
* refetch fails, so the list stays visible alongside the error. -->
* <ul>
* @for (page of projectsQuery.data().pages; track $index) {
* @for (project of page.projects; track project.id) {
* <li>{{ project.name }}</li>
* }
* }
* </ul>
* `,
* })
* export class Projects {
* readonly projectsQuery = injectInfiniteQuery(() => ({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* initialData: { pages: [], pageParams: [] },
* }))
* }
* ```
*/
export function injectInfiniteQuery<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
injectInfiniteQueryFn: () => DefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
options?: InjectInfiniteQueryOptions,
): DefinedCreateInfiniteQueryResult<TData, TError>
/**
* Injects an infinite query: a declarative dependency on an asynchronous source of data that is tied to a
* unique key. Infinite queries can additively "load more" data onto an existing set of data, or
* "infinite scroll".
*
* @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
* refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
* actions, or add conditions like `hasNextPage() && !isFetching()`. This is the only overload that accepts
* `queryFn: skipToken`, shown below.
* @see {@link infiniteQueryOptions} to share these options between `injectInfiniteQuery` and imperative APIs
* like `queryClient.fetchInfiniteQuery`.
* @param injectInfiniteQueryFn - A function returning the {@link UndefinedInitialDataInfiniteOptions} to use
* — everything you can pass to `injectInfiniteQuery`. Similar to `computed` from Angular, this function runs
* in the reactive context, so signals read inside it drive the query.
* @param options - Additional configuration.
* @returns The same signals as `injectQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
* `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data().pages` and
* `data().pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
* `InfiniteData<TQueryFnData>` shape.
*
* @example
* Fetching the next page from a button click:
* ```angular-ts
* @Component({
* selector: 'projects-list',
* template: `
* <ul>
* @for (page of projectsQuery.data()?.pages; track $index) {
* @for (project of page.projects; track project.id) {
* <li>{{ project.name }}</li>
* }
* }
* </ul>
* <button
* [disabled]="!projectsQuery.hasNextPage() || projectsQuery.isFetching()"
* (click)="projectsQuery.fetchNextPage()"
* >
* Load More
* </button>
* `,
* })
* export class ProjectsList {
* readonly projectsQuery = injectInfiniteQuery(() => ({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* }))
* }
* ```
*
* @example
* Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a sentinel
* element after the list:
* ```angular-ts
* @Component({
* selector: 'projects-list',
* template: `
* <ul>
* @for (page of projectsQuery.data()?.pages; track $index) {
* @for (project of page.projects; track project.id) {
* <li>{{ project.name }}</li>
* }
* }
* </ul>
* <div #sentinel>{{ projectsQuery.isFetchingNextPage() ? 'Loading more...' : '' }}</div>
* `,
* })
* export class ProjectsList {
* readonly sentinel = viewChild<ElementRef<HTMLElement>>('sentinel')
*
* readonly projectsQuery = injectInfiniteQuery(() => ({
* queryKey: ['projects'],
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* }))
*
* constructor() {
* effect((onCleanup) => {
* const sentinel = this.sentinel()?.nativeElement
* if (
* sentinel == null ||
* !this.projectsQuery.hasNextPage() ||
* this.projectsQuery.isFetching()
* ) {
* return
* }
*
* const observer = new IntersectionObserver(([entry]) => {
* if (entry?.isIntersecting) this.projectsQuery.fetchNextPage()
* })
* observer.observe(sentinel)
*
* onCleanup(() => observer.disconnect())
* })
* }
* }
* ```
*
* @example
* A query that's disabled, type safe, until `postId` is set — pass `skipToken` as `queryFn` instead of
* setting `enabled: false`:
* ```angular-ts
* @Component({
* selector: 'comments',
* template: `
* @if (postId() == null) {
* Select a post
* } @else if (commentsQuery.isPending()) {
* Loading...
* } @else if (commentsQuery.isError()) {
* <span>Error: {{ commentsQuery.error()?.message }}</span>
* } @else {
* <ul>
* @for (page of commentsQuery.data().pages; track $index) {
* @for (comment of page.comments; track comment.id) {
* <li>{{ comment.text }}</li>
* }
* }
* </ul>
* }
* `,
* })
* export class Comments {
* readonly postId = signal<string | undefined>(undefined)
*
* readonly commentsQuery = injectInfiniteQuery(() => ({
* queryKey: ['post', this.postId(), 'comments'],
* queryFn:
* this.postId() != null
* ? ({ pageParam }) => fetchComments(this.postId()!, pageParam)
* : skipToken,
* initialPageParam: 0,
* getNextPageParam: (lastPage) => lastPage.nextId,
* }))
* }
* ```
*/
export function injectInfiniteQuery<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
injectInfiniteQueryFn: () => UndefinedInitialDataInfiniteOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
options?: InjectInfiniteQueryOptions,
): CreateInfiniteQueryResult<TData, TError>
/**
* This overload accepts the general {@link CreateInfiniteQueryOptions} shape rather than the
* `initialData`-aware overloads above, so whether `data` is defined can't be inferred from the call site —
* useful when wrapping `injectInfiniteQuery` in your own helper function that forwards caller-provided
* options.
*
* @param injectInfiniteQueryFn - A function that returns infinite query options. Similar to `computed` from
* Angular, this function runs in the reactive context, so signals read inside it drive the query.
* @param options - Additional configuration.
* @returns The infinite query result.
*/
export function injectInfiniteQuery<
TQueryFnData,
TError = DefaultError,
TData = InfiniteData<TQueryFnData>,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
>(
injectInfiniteQueryFn: () => CreateInfiniteQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
options?: InjectInfiniteQueryOptions,
): CreateInfiniteQueryResult<TData, TError>
export function injectInfiniteQuery(
injectInfiniteQueryFn: () => CreateInfiniteQueryOptions,
options?: InjectInfiniteQueryOptions,
) {
!options?.injector && assertInInjectionContext(injectInfiniteQuery)
const injector = options?.injector ?? inject(Injector)
return runInInjectionContext(injector, () =>
createBaseQuery(
injectInfiniteQueryFn,
InfiniteQueryObserver as typeof QueryObserver,
),
)
}

View File

@@ -0,0 +1,97 @@
import {
DestroyRef,
Injector,
NgZone,
assertInInjectionContext,
inject,
signal,
} from '@angular/core'
import { QueryClient, notifyManager } from '@tanstack/query-core'
import type { QueryFilters } from '@tanstack/query-core'
import type { Signal } from '@angular/core'
export interface InjectIsFetchingOptions {
/**
* The `Injector` in which to create the isFetching signal.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* Injects a signal that tracks the number of queries that your application is loading or fetching in the
* background (useful for app-wide loading indicators).
*
* @param filters - The {@link QueryFilters} to narrow down the matched queries.
* @param options - Additional configuration
* @returns A `Signal` with the number of queries that your application is currently loading or fetching in
* the background.
*
* @example
* ```angular-ts
* @Component({
* selector: 'posts-fetching-indicator',
* template: `
* @if (isFetchingPosts()) {
* <span>Refreshing posts...</span>
* }
* `,
* })
* export class PostsFetchingIndicator {
* // How many queries matching the posts prefix are fetching?
* readonly isFetchingPosts = injectIsFetching({ queryKey: ['posts'] })
* }
* ```
*
* @example
* A global loading indicator for any query fetching in the background, not just the ones on screen:
* ```angular-ts
* @Component({
* selector: 'global-loading-indicator',
* template: `
* @if (isFetching()) {
* <div>Queries are fetching in the background...</div>
* }
* `,
* })
* export class GlobalLoadingIndicator {
* readonly isFetching = injectIsFetching()
* }
* ```
*/
export function injectIsFetching(
filters?: QueryFilters,
options?: InjectIsFetchingOptions,
): Signal<number> {
!options?.injector && assertInInjectionContext(injectIsFetching)
const injector = options?.injector ?? inject(Injector)
const destroyRef = injector.get(DestroyRef)
const ngZone = injector.get(NgZone)
const queryClient = injector.get(QueryClient)
const cache = queryClient.getQueryCache()
// isFetching is the prev value initialized on mount *
let isFetching = queryClient.isFetching(filters)
const result = signal(isFetching)
const unsubscribe = ngZone.runOutsideAngular(() =>
cache.subscribe(
notifyManager.batchCalls(() => {
const newIsFetching = queryClient.isFetching(filters)
if (isFetching !== newIsFetching) {
// * and update with each change
isFetching = newIsFetching
ngZone.run(() => {
result.set(isFetching)
})
}
}),
),
)
destroyRef.onDestroy(unsubscribe)
return result
}

View File

@@ -0,0 +1,80 @@
import {
DestroyRef,
Injector,
NgZone,
assertInInjectionContext,
inject,
signal,
} from '@angular/core'
import { QueryClient, notifyManager } from '@tanstack/query-core'
import type { MutationFilters } from '@tanstack/query-core'
import type { Signal } from '@angular/core'
export interface InjectIsMutatingOptions {
/**
* The `Injector` in which to create the isMutating signal.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* Injects a signal that tracks the number of mutations that your application currently has `pending`
* (useful for app-wide loading indicators).
*
* @param filters - The {@link MutationFilters} to narrow down the matched mutations.
* @param options - Additional configuration
* @returns A `Signal` with the number of mutations that your application currently has `pending`.
*
* @example
* ```angular-ts
* @Component({
* selector: 'posts-mutating-indicator',
* template: `
* @if (isMutatingPosts()) {
* <span>Saving posts...</span>
* }
* `,
* })
* export class PostsMutatingIndicator {
* // How many mutations matching the posts prefix are in progress?
* readonly isMutatingPosts = injectIsMutating({ mutationKey: ['posts'] })
* }
* ```
*/
export function injectIsMutating(
filters?: MutationFilters,
options?: InjectIsMutatingOptions,
): Signal<number> {
!options?.injector && assertInInjectionContext(injectIsMutating)
const injector = options?.injector ?? inject(Injector)
const destroyRef = injector.get(DestroyRef)
const ngZone = injector.get(NgZone)
const queryClient = injector.get(QueryClient)
const cache = queryClient.getMutationCache()
// isMutating is the prev value initialized on mount *
let isMutating = queryClient.isMutating(filters)
const result = signal(isMutating)
const unsubscribe = ngZone.runOutsideAngular(() =>
cache.subscribe(
notifyManager.batchCalls(() => {
const newIsMutating = queryClient.isMutating(filters)
if (isMutating !== newIsMutating) {
// * and update with each change
isMutating = newIsMutating
ngZone.run(() => {
result.set(isMutating)
})
}
}),
),
)
destroyRef.onDestroy(unsubscribe)
return result.asReadonly()
}

View File

@@ -0,0 +1,53 @@
import {
InjectionToken,
Injector,
assertInInjectionContext,
inject,
signal,
} from '@angular/core'
import type { Provider, Signal } from '@angular/core'
/**
* Internal token used to track isRestoring state, accessible in public API through `injectIsRestoring` and set via `provideIsRestoring`
*/
const IS_RESTORING = new InjectionToken('', {
// Default value when not provided
factory: () => signal(false).asReadonly(),
})
interface InjectIsRestoringOptions {
/**
* The `Injector` to use to get the isRestoring signal.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* Injects a signal that tracks whether a restore (e.g. from a persisted client, wired up via
* `provideIsRestoring`) is currently in progress. `injectQuery` and friends also check this internally to
* avoid race conditions between the restore and initializing queries.
* @param options - Additional configuration
* @returns A readonly `Signal<boolean>` — `true` while a restore is in progress, `false` otherwise (the
* default when no `provideIsRestoring` provider is registered).
*/
export function injectIsRestoring(options?: InjectIsRestoringOptions) {
!options?.injector && assertInInjectionContext(injectIsRestoring)
const injector = options?.injector ?? inject(Injector)
return injector.get(IS_RESTORING)
}
/**
* Registers a provider for the restore state read by `injectIsRestoring`. Wire this up wherever you drive a
* restore yourself — e.g. a persist-client integration — so `injectQuery` and friends can defer subscribing
* to their observer (avoiding a race with the restore) until the restore signal flips back to `false`.
* @param isRestoring - A readonly `Signal<boolean>` that tracks the restore state.
* @returns A provider for the `isRestoring` signal.
*/
export function provideIsRestoring(isRestoring: Signal<boolean>): Provider {
return {
provide: IS_RESTORING,
useValue: isRestoring,
}
}

View File

@@ -0,0 +1,167 @@
import {
DestroyRef,
Injector,
NgZone,
assertInInjectionContext,
computed,
inject,
signal,
} from '@angular/core'
import {
QueryClient,
notifyManager,
replaceEqualDeep,
} from '@tanstack/query-core'
import type { Signal } from '@angular/core'
import type {
Mutation,
MutationCache,
MutationFilters,
MutationState,
} from '@tanstack/query-core'
type MutationStateOptions<TResult = MutationState> = {
filters?: MutationFilters
select?: (mutation: Mutation) => TResult
}
function getResult<TResult = MutationState>(
mutationCache: MutationCache,
options: MutationStateOptions<TResult>,
): Array<TResult> {
return mutationCache
.findAll(options.filters)
.map(
(mutation): TResult =>
(options.select ? options.select(mutation) : mutation.state) as TResult,
)
}
export interface InjectMutationStateOptions {
/**
* The `Injector` in which to create the mutation state signal.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`
* ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation state.
*
* @param injectMutationStateFn - A function returning the `filters` to narrow down matched mutations, and an
* optional `select` to transform the mutation state. Similar to `computed` from Angular, this function runs
* in the reactive context, so signals read inside it re-narrow the matched mutations.
* @param options - Additional configuration
* @returns A `Signal` with an Array of whatever `select` returns for each matching mutation.
*
* @example
* Get all variables of all running mutations:
* ```angular-ts
* @Component({
* selector: 'pending-posts',
* template: `{{ pendingVariables().length }} posts saving...`,
* })
* export class PendingPosts {
* readonly pendingVariables = injectMutationState(() => ({
* filters: { status: 'pending' },
* select: (mutation) => mutation.state.variables,
* }))
* }
* ```
*
* @example
* Get all data for specific mutations via the `mutationKey`:
* ```angular-ts
* const mutationKey = ['posts']
*
* @Component({
* selector: 'posts',
* template: `
* <button (click)="createPost()">
* Create post ({{ savedPosts().length }} saved so far)
* </button>
* `,
* })
* export class Posts {
* // Some mutation that we want to get the state for
* readonly createPostMutation = injectMutation(() => ({
* mutationKey,
* mutationFn: createPosts,
* }))
*
* readonly savedPosts = injectMutationState(() => ({
* // this mutation key needs to match the mutation key of the given mutation (see above)
* filters: { mutationKey, status: 'success' },
* select: (mutation) => mutation.state.data,
* }))
*
* createPost() {
* this.createPostMutation.mutate(['New Post'])
* }
* }
* ```
*/
export function injectMutationState<TResult = MutationState>(
injectMutationStateFn: () => MutationStateOptions<TResult> = () => ({}),
options?: InjectMutationStateOptions,
): Signal<Array<TResult>> {
!options?.injector && assertInInjectionContext(injectMutationState)
const injector = options?.injector ?? inject(Injector)
const destroyRef = injector.get(DestroyRef)
const ngZone = injector.get(NgZone)
const queryClient = injector.get(QueryClient)
const mutationCache = queryClient.getMutationCache()
/**
* Computed signal that gets result from mutation cache based on passed options
* First element is the result, second element is the time when the result was set
*/
const resultFromOptionsSignal = computed(() => {
return [
getResult(mutationCache, injectMutationStateFn()),
performance.now(),
] as const
})
/**
* Signal that contains result set by subscriber
* First element is the result, second element is the time when the result was set
*/
const resultFromSubscriberSignal = signal<[Array<TResult>, number] | null>(
null,
)
/**
* Returns the last result by either subscriber or options
*/
const effectiveResultSignal = computed(() => {
const optionsResult = resultFromOptionsSignal()
const subscriberResult = resultFromSubscriberSignal()
return subscriberResult && subscriberResult[1] > optionsResult[1]
? subscriberResult[0]
: optionsResult[0]
})
const unsubscribe = ngZone.runOutsideAngular(() =>
mutationCache.subscribe(
notifyManager.batchCalls(() => {
const [lastResult] = effectiveResultSignal()
const nextResult = replaceEqualDeep(
lastResult,
getResult(mutationCache, injectMutationStateFn()),
)
if (lastResult !== nextResult) {
ngZone.run(() => {
resultFromSubscriberSignal.set([nextResult, performance.now()])
})
}
}),
),
)
destroyRef.onDestroy(unsubscribe)
return effectiveResultSignal
}

View File

@@ -0,0 +1,328 @@
import {
Injector,
NgZone,
assertInInjectionContext,
computed,
effect,
inject,
signal,
untracked,
} from '@angular/core'
import {
MutationObserver,
QueryClient,
noop,
notifyManager,
shouldThrowError,
} from '@tanstack/query-core'
import { signalProxy } from './signal-proxy'
import { PENDING_TASKS } from './pending-tasks-compat'
import type { PendingTaskRef } from './pending-tasks-compat'
import type { DefaultError, MutationObserverResult } from '@tanstack/query-core'
import type {
CreateMutateFunction,
CreateMutationOptions,
CreateMutationResult,
} from './types'
export interface InjectMutationOptions {
/**
* The `Injector` in which to create the mutation.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
* `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
*
* @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
* second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
* the shared mutation definition. Callbacks defined in `injectMutationFn` fire for every mutation; per-call
* callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,
* so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
* @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
* the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
* @param injectMutationFn - A function that returns mutation options. Similar to `computed` from Angular,
* this function runs in the reactive context, so signals read inside it drive the mutation's options.
* @param options - Additional configuration
* @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them
* (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
* unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
* `data` is defined.
*
* @example
* ```angular-ts
* @Component({
* selector: 'todos',
* template: `
* @if (addMutation.isPending()) {
* <span>Adding todo...</span>
* } @else if (addMutation.isError()) {
* <div>An error occurred: {{ addMutation.error()?.message }}</div>
* }
* <button (click)="addMutation.mutate('Item')">Add</button>
* `,
* })
* export class Todos {
* readonly #queryClient = inject(QueryClient)
*
* readonly addMutation = injectMutation(() => ({
* mutationFn: addTodo,
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
* }))
* }
* ```
*
* @example
* Optimistic update via `onMutate`, rolling back on `onError`:
* ```angular-ts
* @Component({
* selector: 'todos',
* template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
* })
* export class Todos {
* readonly #queryClient = inject(QueryClient)
*
* readonly addMutation = injectMutation(() => ({
* mutationFn: addTodo,
* onMutate: async (newTodo) => {
* await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
* const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
*
* this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
* ...(old ?? []),
* newTodo,
* ])
*
* // Passed to `onError` as `onMutateResult` if the mutation fails.
* return { previousTodos }
* },
* onError: (_err, _newTodo, onMutateResult) => {
* this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
* },
* onSettled: () => {
* this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
* },
* }))
* }
* ```
*
* @example
* Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per
* call instead, so you can wait for all of them when they succeed:
* ```angular-ts
* @Component({
* selector: 'todos',
* template: `
* <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
* `,
* })
* export class Todos {
* readonly #queryClient = inject(QueryClient)
*
* readonly addMutation = injectMutation(() => ({
* mutationFn: addTodo,
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
* }))
*
* async handleAddAll(todos: Array<string>) {
* try {
* await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
* } catch (error) {
* console.error('Failed to add todos:', error)
* }
* }
* }
* ```
*
* @example
* If some of the mutations above can fail independently of the others, and you want to know which ones did —
* rather than losing that information the moment the first one rejects — swap `Promise.all` for
* `Promise.allSettled`:
* ```angular-ts
* @Component({
* selector: 'todos',
* template: `
* <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
* `,
* })
* export class Todos {
* readonly #queryClient = inject(QueryClient)
*
* readonly addMutation = injectMutation(() => ({
* mutationFn: addTodo,
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
* }))
*
* async handleAddAll(todos: Array<string>) {
* const addResults = await Promise.allSettled(
* todos.map((todo) => this.addMutation.mutateAsync(todo)),
* )
*
* addResults.forEach((addResult, index) => {
* if (addResult.status === 'rejected') {
* console.error(`Failed to add "${todos[index]}":`, addResult.reason)
* }
* })
* }
* }
* ```
*/
export function injectMutation<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
>(
injectMutationFn: () => CreateMutationOptions<
TData,
TError,
TVariables,
TOnMutateResult
>,
options?: InjectMutationOptions,
): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {
!options?.injector && assertInInjectionContext(injectMutation)
const injector = options?.injector ?? inject(Injector)
const ngZone = injector.get(NgZone)
const pendingTasks = injector.get(PENDING_TASKS)
const queryClient = injector.get(QueryClient)
/**
* computed() is used so signals can be inserted into the options
* making it reactive. Wrapping options in a function ensures embedded expressions
* are preserved and can keep being applied after signal changes
*/
const optionsSignal = computed(injectMutationFn)
const observerSignal = (() => {
let instance: MutationObserver<
TData,
TError,
TVariables,
TOnMutateResult
> | null = null
return computed(() => {
return (instance ||= new MutationObserver(queryClient, optionsSignal()))
})
})()
const mutateFnSignal = computed<
CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
>(() => {
const observer = observerSignal()
return (
...args: Parameters<
CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
>
) => {
observer.mutate(args[0] as TVariables, args[1]).catch(noop)
}
})
/**
* Computed signal that gets result from mutation cache based on passed options
*/
const resultFromInitialOptionsSignal = computed(() => {
const observer = observerSignal()
return observer.getCurrentResult()
})
/**
* Signal that contains result set by subscriber
*/
const resultFromSubscriberSignal = signal<MutationObserverResult<
TData,
TError,
TVariables,
TOnMutateResult
> | null>(null)
effect(
() => {
const observer = observerSignal()
const observerOptions = optionsSignal()
untracked(() => {
observer.setOptions(observerOptions)
})
},
{
injector,
},
)
effect(
(onCleanup) => {
// observer.trackResult is not used as this optimization is not needed for Angular
const observer = observerSignal()
let pendingTaskRef: PendingTaskRef | null = null
untracked(() => {
const unsubscribe = ngZone.runOutsideAngular(() =>
observer.subscribe(
notifyManager.batchCalls((state) => {
ngZone.run(() => {
// Track pending task when mutation is pending
if (state.isPending && !pendingTaskRef) {
pendingTaskRef = pendingTasks.add()
}
// Clear pending task when mutation is no longer pending
if (!state.isPending && pendingTaskRef) {
pendingTaskRef()
pendingTaskRef = null
}
if (
state.isError &&
shouldThrowError(observer.options.throwOnError, [state.error])
) {
ngZone.onError.emit(state.error)
throw state.error
}
resultFromSubscriberSignal.set(state)
})
}),
),
)
onCleanup(() => {
// Clean up any pending task on destroy
if (pendingTaskRef) {
pendingTaskRef()
pendingTaskRef = null
}
unsubscribe()
})
})
},
{
injector,
},
)
const resultSignal = computed(() => {
const resultFromSubscriber = resultFromSubscriberSignal()
const resultFromInitialOptions = resultFromInitialOptionsSignal()
const result = resultFromSubscriber ?? resultFromInitialOptions
return {
...result,
mutate: mutateFnSignal(),
mutateAsync: result.mutate,
}
})
return signalProxy(resultSignal) as CreateMutationResult<
TData,
TError,
TVariables,
TOnMutateResult
>
}

View File

@@ -0,0 +1 @@
export * from '../inject-queries'

View File

@@ -0,0 +1,479 @@
import {
QueriesObserver,
QueryClient,
notifyManager,
} from '@tanstack/query-core'
import {
DestroyRef,
Injector,
NgZone,
assertInInjectionContext,
computed,
effect,
inject,
runInInjectionContext,
signal,
untracked,
} from '@angular/core'
import { signalProxy } from './signal-proxy'
import { injectIsRestoring } from './inject-is-restoring'
import type {
DefaultError,
OmitKeyof,
QueriesObserverOptions,
QueriesPlaceholderDataFunction,
QueryFunction,
QueryKey,
QueryObserverOptions,
ThrowOnError,
} from '@tanstack/query-core'
import type {
CreateQueryOptions,
CreateQueryResult,
DefinedCreateQueryResult,
} from './types'
import type { Signal } from '@angular/core'
// This defines the `CreateQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
// `placeholderData` function always gets undefined passed
type QueryObserverOptionsForCreateQueries<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = OmitKeyof<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'placeholderData'
> & {
placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>
}
// Avoid TS depth-limit error in case of large array literal
type MAXIMUM_DEPTH = 20
// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
type SkipTokenForCreateQueries = symbol
type GetCreateQueryOptionsForCreateQueries<T> =
// Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
T extends {
queryFnData: infer TQueryFnData
error?: infer TError
data: infer TData
}
? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>
: T extends { queryFnData: infer TQueryFnData; error?: infer TError }
? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>
: T extends { data: infer TData; error?: infer TError }
? QueryObserverOptionsForCreateQueries<unknown, TError, TData>
: // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, 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>
: // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, infer TQueryKey>
| SkipTokenForCreateQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? QueryObserverOptionsForCreateQueries<
TQueryFnData,
unknown extends TError ? DefaultError : TError,
unknown extends TData ? TQueryFnData : TData,
TQueryKey
>
: // Fallback
QueryObserverOptionsForCreateQueries
// A defined initialData setting should return a DefinedCreateQueryResult rather than CreateQueryResult
type GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {
initialData?: infer TInitialData
}
? 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>
type GetCreateQueryResult<T> =
// Part 1: responsible for mapping explicit type parameter to function result, if object
T extends { queryFnData: any; error?: infer TError; data: infer TData }
? GetDefinedOrUndefinedQueryResult<T, TData, TError>
: T extends { queryFnData: infer TQueryFnData; error?: infer TError }
? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
: T extends { data: infer TData; error?: infer TError }
? GetDefinedOrUndefinedQueryResult<T, TData, TError>
: // Part 2: responsible for mapping explicit type parameter to function result, if tuple
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>
: // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
T extends {
queryFn?:
| QueryFunction<infer TQueryFnData, any>
| SkipTokenForCreateQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
}
? GetDefinedOrUndefinedQueryResult<
T,
unknown extends TData ? TQueryFnData : TData,
unknown extends TError ? DefaultError : TError
>
: // Fallback
CreateQueryResult
/**
* The `queries` array accepted by `injectQueries`. Recursively unwraps each tuple element so every entry's
* `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements — past that, tuple
* recursion falls back to a single homogeneous options type. An opaque array (e.g. `unknown[]`) is returned
* as-is; a non-tuple array of a known element type is mapped to that element type instead, with no such
* limit.
*
* @template T - The type of the `queries` array as written at the call site.
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
* be set explicitly.
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
* meant to be set explicitly.
*/
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<
[...Tails],
[...TResults, GetCreateQueryOptionsForCreateQueries<Head>],
[...TDepth, 1]
>
: ReadonlyArray<unknown> extends T
? T
: // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
// use this to infer the param types in the case of Array.map() argument
T extends Array<
QueryObserverOptionsForCreateQueries<
infer TQueryFnData,
infer TError,
infer TData,
infer TQueryKey
>
>
? Array<
QueryObserverOptionsForCreateQueries<
TQueryFnData,
TError,
TData,
TQueryKey
>
>
: // Fallback
Array<QueryObserverOptionsForCreateQueries>
/**
* The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:
* each tuple element's result type is inferred individually, up to 20 elements — past that, tuple recursion
* falls back to a single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped per-element
* instead, with no such limit — every entry keeps its individually inferred type regardless of array length.
*
* @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
* @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
* be set explicitly.
* @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
* meant to be set explicitly.
*/
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<
[...Tails],
[...TResults, GetCreateQueryResult<Head>],
[...TDepth, 1]
>
: { [K in keyof T]: GetCreateQueryResult<T[K]> }
export interface InjectQueriesOptions<
T extends Array<any>,
TCombinedResult = QueriesResults<T>,
> {
queries:
| readonly [...QueriesOptions<T>]
| readonly [
...{ [K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]> },
]
combine?: (result: QueriesResults<T>) => TCombinedResult
}
/**
* Injects a signal to fetch a variable number of queries.
*
* The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
* the same query key more than once in the array of query objects may cause some data to be shared between
* queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
* structure.
*
* The `combine` option can be used to combine the results of the queries into a single value. The result
* will be structurally shared to be as referentially stable as possible.
*
* @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
* from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
* the `select` parameter of a query object written inline cannot be contextually typed from that same
* object's `queryFn`, so it falls back to `unknown` — a
* [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
* parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
* object _before_ it reaches `injectQueries`, to work around this — see the example below.
* @param optionsFn - A function returning the queries' options — an array of query option objects under
* `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
* reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
* @param injector - The `Injector` in which to create the queries. If this is not provided, the current
* injection context will be used instead (via `inject`).
* @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
* results, in the same order as the input. When `combine` is provided, this is the value returned by
* `combine` instead.
*
* @example
* ```angular-ts
* @Component({
* selector: 'posts',
* template: `
* <ul>
* @for (query of postQueries(); track $index) {
* @if (query.isPending()) {
* <li>Loading...</li>
* } @else if (query.isError()) {
* <li>Error: {{ query.error()?.message }}</li>
* } @else {
* <li>{{ query.data().title }}</li>
* }
* }
* </ul>
* `,
* })
* export class Posts {
* readonly ids = signal([1, 2, 3])
*
* readonly postQueries = injectQueries(() => ({
* queries: this.ids().map((id) => ({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* staleTime: Infinity,
* })),
* }))
* }
* ```
*
* @example
* Combining results into a single value:
* ```angular-ts
* @Component({
* selector: 'posts',
* template: `
* @if (combined().isPending) {
* Loading...
* } @else if (combined().isError) {
* Error loading posts
* } @else {
* <ul>
* @for (post of combined().data; track post?.id) {
* <li>{{ post?.title }}</li>
* }
* </ul>
* }
* `,
* })
* export class Posts {
* readonly ids = signal([1, 2, 3])
*
* readonly combined = injectQueries(() => ({
* queries: this.ids().map((id) => ({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })),
* combine: (postQueries) => ({
* data: postQueries.map((query) => query.data),
* isPending: postQueries.some((query) => query.isPending),
* isError: postQueries.some((query) => query.isError),
* }),
* }))
* }
* ```
*
* @example
* Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
* `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
* resolved before it reaches `injectQueries`:
* ```angular-ts
* const postOptions = (id: number) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* @Component({
* selector: 'post-title',
* template: `<h1>{{ fixed()[0].data() }}</h1>`,
* })
* export class PostTitle {
* readonly id = signal(1)
*
* readonly broken = injectQueries(() => ({
* queries: [
* {
* ...postOptions(this.id()),
* // ❌ `data` is `unknown` here
* select: (data) => data.title,
* },
* ],
* }))
*
* readonly fixed = injectQueries(() => ({
* queries: [
* queryOptions({
* ...postOptions(this.id()),
* // ✅ `data` is `Post`
* select: (data) => data.title,
* }),
* ],
* }))
* }
* ```
*/
export function injectQueries<
T extends Array<any>,
TCombinedResult = QueriesResults<T>,
>(
optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,
injector?: Injector,
): Signal<TCombinedResult> {
!injector && assertInInjectionContext(injectQueries)
return runInInjectionContext(injector ?? inject(Injector), () => {
const destroyRef = inject(DestroyRef)
const ngZone = inject(NgZone)
const queryClient = inject(QueryClient)
const isRestoring = injectIsRestoring()
/**
* Signal that has the default options from query client applied
* computed() is used so signals can be inserted into the options
* making it reactive. Wrapping options in a function ensures embedded expressions
* are preserved and can keep being applied after signal changes
*/
const optionsSignal = computed(() => {
return optionsFn()
})
const defaultedQueries = computed(() => {
return optionsSignal().queries.map((opts) => {
const defaultedOptions = queryClient.defaultQueryOptions(
opts as QueryObserverOptions,
)
// Make sure the results are already in fetching state before subscribing or updating options
defaultedOptions._optimisticResults = isRestoring()
? 'isRestoring'
: 'optimistic'
return defaultedOptions as QueryObserverOptions
})
})
const observerSignal = (() => {
let instance: QueriesObserver<TCombinedResult> | null = null
return computed(() => {
return (instance ||= new QueriesObserver<TCombinedResult>(
queryClient,
defaultedQueries(),
optionsSignal() as QueriesObserverOptions<TCombinedResult>,
))
})
})()
const optimisticResultSignal = computed(() =>
observerSignal().getOptimisticResult(
defaultedQueries(),
(optionsSignal() as QueriesObserverOptions<TCombinedResult>).combine,
),
)
// Do not notify on updates because of changes in the options because
// these changes should already be reflected in the optimistic result.
effect(() => {
observerSignal().setQueries(
defaultedQueries(),
optionsSignal() as QueriesObserverOptions<TCombinedResult>,
)
})
const optimisticCombinedResultSignal = computed(() => {
const [_optimisticResult, getCombinedResult, trackResult] =
optimisticResultSignal()
return getCombinedResult(trackResult())
})
const resultFromSubscriberSignal = signal<TCombinedResult | null>(null)
effect(() => {
const observer = observerSignal()
const [_optimisticResult, getCombinedResult] = optimisticResultSignal()
untracked(() => {
const unsubscribe = isRestoring()
? () => undefined
: ngZone.runOutsideAngular(() =>
observer.subscribe(
notifyManager.batchCalls((state) => {
resultFromSubscriberSignal.set(getCombinedResult(state))
}),
),
)
destroyRef.onDestroy(unsubscribe)
})
})
const resultSignal = computed(() => {
const subscriberResult = resultFromSubscriberSignal()
const optimisticResult = optimisticCombinedResultSignal()
return subscriberResult ?? optimisticResult
})
return computed(() => {
const result = resultSignal()
const { combine } = optionsSignal()
return combine
? result
: (result as QueriesResults<T>).map((query) =>
signalProxy(signal(query)),
)
})
}) as unknown as Signal<TCombinedResult>
}

View File

@@ -0,0 +1,22 @@
import { Injector, inject } from '@angular/core'
import { QueryClient } from '@tanstack/query-core'
import type { InjectOptions } from '@angular/core'
/**
* Injects a `QueryClient` instance and allows passing a custom injector.
* @param injectOptions - Type of the options argument to inject and optionally a custom injector.
* @returns The `QueryClient` instance.
* @deprecated Use `inject(QueryClient)` instead.
* If you need to get a `QueryClient` from a custom injector, use `injector.get(QueryClient)`.
*
*
* **Example**
* ```ts
* const queryClient = injectQueryClient();
* ```
*/
export function injectQueryClient(
injectOptions: InjectOptions & { injector?: Injector } = {},
) {
return (injectOptions.injector ?? inject(Injector)).get(QueryClient)
}

View File

@@ -0,0 +1,208 @@
import { QueryObserver } from '@tanstack/query-core'
import {
Injector,
assertInInjectionContext,
inject,
runInInjectionContext,
} from '@angular/core'
import { createBaseQuery } from './create-base-query'
import type { DefaultError, QueryKey } from '@tanstack/query-core'
import type {
CreateQueryOptions,
CreateQueryResult,
DefinedCreateQueryResult,
} from './types'
import type {
DefinedInitialDataOptions,
UndefinedInitialDataOptions,
} from './query-options'
export interface InjectQueryOptions {
/**
* The `Injector` in which to create the query.
*
* If this is not provided, the current injection context will be used instead (via `inject`).
*/
injector?: Injector
}
/**
* This overload is selected when `initialData` is set on the options returned by `injectQueryFn`, so the
* resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).
*
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
* @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
* `queryClient.fetchQuery`.
* @param injectQueryFn - A function returning the {@link DefinedInitialDataOptions} to use — everything you
* can pass to `injectQuery`, with `initialData` set. Similar to `computed` from Angular, this function runs
* in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
* @param options - Additional configuration
* @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to
* include `undefined`).
*
* @example
* ```angular-ts
* @Component({
* selector: 'posts',
* template: `
* <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` — even if a
* refetch fails, so the list stays visible alongside the error. -->
* @if (postsQuery.isError()) {
* <span>Error: {{ postsQuery.error()?.message }}</span>
* }
* <ul>
* @for (post of postsQuery.data(); track post.id) {
* <li>{{ post.title }}</li>
* }
* </ul>
* `,
* })
* export class Posts {
* readonly postsQuery = injectQuery(() => ({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* initialData: [],
* }))
* }
* ```
*/
export function injectQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
injectQueryFn: () => DefinedInitialDataOptions<
TQueryFnData,
TError,
TData,
TQueryKey
>,
options?: InjectQueryOptions,
): DefinedCreateQueryResult<TData, TError>
/**
* Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
*
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
* @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
* `queryClient.fetchQuery`.
* @param injectQueryFn - A function returning the {@link UndefinedInitialDataOptions} to use — everything
* you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive
* context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
* @param options - Additional configuration
* @returns The query result. `status()` is `'pending'` if there is no cached data to display, `'error'` if
* the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/
* `isError` are type-guard methods for convenience.
*
* @example
* ```angular-ts
* @Component({
* selector: 'posts',
* template: `
* @if (postsQuery.isPending()) {
* Loading...
* } @else if (postsQuery.isError()) {
* <span>Error: {{ postsQuery.error()?.message }}</span>
* } @else {
* <ul>
* @for (post of postsQuery.data(); track post.id) {
* <li>{{ post.title }}</li>
* }
* </ul>
* }
* `,
* })
* export class Posts {
* readonly postsQuery = injectQuery(() => ({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* }))
* }
* ```
*
* @example
* Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In
* the example below, the query is automatically enabled and executed when the filter signal changes to a
* truthy value. When the filter signal changes back to a falsy value, the query is disabled.
* ```angular-ts
* @Component({
* selector: 'posts',
* template: `
* <input [ngModel]="filter()" (ngModelChange)="filter.set($event)" />
* @if (postsQuery.isPending()) {
* Loading...
* } @else if (postsQuery.isError()) {
* <span>Error: {{ postsQuery.error()?.message }}</span>
* } @else {
* <ul>
* @for (post of postsQuery.data(); track post.id) {
* <li>{{ post.title }}</li>
* }
* </ul>
* }
* `,
* })
* export class Posts {
* readonly filter = signal('')
*
* readonly postsQuery = injectQuery(() => ({
* queryKey: ['posts', this.filter()],
* queryFn: () => fetchPosts(this.filter()),
* // Signals can be combined with expressions
* enabled: !!this.filter(),
* }))
* }
* ```
*/
export function injectQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
injectQueryFn: () => UndefinedInitialDataOptions<
TQueryFnData,
TError,
TData,
TQueryKey
>,
options?: InjectQueryOptions,
): CreateQueryResult<TData, TError>
/**
* This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware
* overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping
* `injectQuery` in your own helper function that forwards caller-provided options.
*
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
* @param injectQueryFn - A function that returns query options. Similar to `computed` from Angular, this
* function runs in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive
* the query.
* @param options - Additional configuration
* @returns The query result.
*/
export function injectQuery<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
injectQueryFn: () => CreateQueryOptions<
TQueryFnData,
TError,
TData,
TQueryKey
>,
options?: InjectQueryOptions,
): CreateQueryResult<TData, TError>
export function injectQuery(
injectQueryFn: () => CreateQueryOptions,
options?: InjectQueryOptions,
) {
!options?.injector && assertInInjectionContext(injectQuery)
return runInInjectionContext(options?.injector ?? inject(Injector), () =>
createBaseQuery(injectQueryFn, QueryObserver),
) as unknown as CreateQueryResult
}

View File

@@ -0,0 +1,121 @@
import type { DefaultError, WithRequired } from '@tanstack/query-core'
import type { CreateMutationOptions } from './types'
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. A
* `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
* `injectMutationState`.
*
* @see {@link injectMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, with a
* required `mutationKey`.
* @returns The same options object, unchanged.
*
* @example
* Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
* ```angular-ts
* import { mutationOptions, injectMutationState } from '@tanstack/angular-query-experimental'
*
* const createPostOptions = mutationOptions({
* mutationKey: ['posts', 'create'],
* mutationFn: createPost,
* })
*
* @Component({
* selector: 'saving-indicator',
* template: `
* @if (isCreatingPost()) {
* <span>Saving…</span>
* }
* `,
* })
* export class SavingIndicator {
* readonly #pendingCreates = injectMutationState(() => ({
* filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
* }))
* readonly isCreatingPost = computed(() => this.#pendingCreates().length > 0)
* }
* ```
*/
export 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'
>
/**
* You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. No
* `mutationKey` is required on this overload — use this when you don't need to target the mutation via a
* `mutationKey` filter later (e.g. with `injectMutationState`); it can still be observed through other
* filters, such as `status`.
*
* @see {@link injectMutation} to run the mutation these options describe.
* @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, without a
* `mutationKey`.
* @returns The same options object, unchanged.
* @remarks See the other overload's example for looking a mutation up via `injectMutationState`.
*
* @example
* Sharing options across services, so `QueriesService` stays the single place a mutation is defined:
* ```angular-ts
* import { mutationOptions, injectMutation } from '@tanstack/angular-query-experimental'
*
* @Injectable({ providedIn: 'root' })
* export class QueriesService {
* readonly #queryClient = inject(QueryClient)
*
* updatePost(id: number) {
* return mutationOptions({
* mutationFn: (post: Partial<Post>) => putPost(id, post),
* onSuccess: (newPost) => this.#queryClient.setQueryData(['posts', id], newPost),
* })
* }
* }
*
* @Component({
* selector: 'post',
* template: `<button (click)="save()">Save</button>`,
* })
* export class Post {
* readonly queries = inject(QueriesService)
* readonly id = signal(0)
* readonly updatePostMutation = injectMutation(() => this.queries.updatePost(this.id()))
*
* save() {
* this.updatePostMutation.mutate({ title: 'New Title' })
* }
* }
* ```
*/
export 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'
>
export function mutationOptions<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
>(
options: CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,
): CreateMutationOptions<TData, TError, TVariables, TOnMutateResult> {
return options
}

View File

@@ -0,0 +1,28 @@
import { InjectionToken, inject } from '@angular/core'
import * as ng from '@angular/core'
import { noop } from '@tanstack/query-core'
type PendingTasksCompat = { add: () => PendingTaskRef }
export type PendingTaskRef = () => void
export const PENDING_TASKS = new InjectionToken<PendingTasksCompat>(
'PENDING_TASKS',
{
factory: (): PendingTasksCompat => {
// Access via Reflect so bundlers stay quiet when the token is absent (Angular < 19).
const token = Reflect.get(ng, 'PendingTasks') as unknown as
| Parameters<typeof inject>[0]
| undefined
const svc: PendingTasksCompat | null = token
? (inject(token, { optional: true }) as PendingTasksCompat | null)
: null
// Without PendingTasks we fall back to a stable no-op shim.
return {
add: svc ? () => svc.add() : () => noop,
}
},
},
)

View File

@@ -0,0 +1,170 @@
import { DestroyRef, InjectionToken, inject } from '@angular/core'
import { QueryClient } from '@tanstack/query-core'
import type { Provider } from '@angular/core'
/**
* Usually {@link provideTanStackQuery} is used once to set up TanStack Query and the
* [`QueryClient`](https://tanstack.com/query/latest/docs/reference/QueryClient) for the entire application —
* it calls `provideQueryClient` internally. Use `provideQueryClient` directly to provide a different
* `QueryClient` instance for part of the application, or for unit testing.
* @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
* @returns A provider object that can be used to provide the `QueryClient` instance.
*
* @example
* Providing a test-only `QueryClient` in a component test, without wiring up `provideTanStackQuery`'s other
* defaults:
* ```ts
* TestBed.configureTestingModule({
* providers: [provideQueryClient(new QueryClient())],
* })
* ```
*/
export function provideQueryClient(
queryClient: QueryClient | InjectionToken<QueryClient>,
): Provider {
return {
provide: QueryClient,
useFactory: () => {
const client =
queryClient instanceof InjectionToken
? inject(queryClient)
: queryClient
// Unmount the query client on injector destroy
inject(DestroyRef).onDestroy(() => client.unmount())
client.mount()
return client
},
}
}
/**
* Sets up providers necessary to enable TanStack Query functionality for Angular applications. Allows
* configuring a `QueryClient` and optional features such as developer tools.
*
* @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
* @see {@link withDevtools}
* @param queryClient - A `QueryClient` instance, or an `InjectionToken` which provides a `QueryClient`.
* @param features - Optional features to configure additional Query functionality.
* @returns A set of providers to set up TanStack Query.
*
* @example
* ```ts
* import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'
*
* bootstrapApplication(AppComponent, {
* providers: [provideTanStackQuery(new QueryClient())],
* })
* ```
*
* @example
* The same, in an `NgModule`-based application:
* ```ts
* import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'
*
* @NgModule({
* declarations: [AppComponent],
* imports: [BrowserModule],
* providers: [provideTanStackQuery(new QueryClient())],
* bootstrap: [AppComponent],
* })
* export class AppModule {}
* ```
*
* @example
* Enabling optional developer tools by adding `withDevtools` — by default, the tools are then loaded when
* your app is in development mode:
* ```ts
* import {
* provideTanStackQuery,
* withDevtools,
* QueryClient,
* } from '@tanstack/angular-query-experimental'
*
* bootstrapApplication(AppComponent, {
* providers: [provideTanStackQuery(new QueryClient(), withDevtools())],
* })
* ```
*
* @example
* Using an `InjectionToken` for the `QueryClient` — an advanced optimization that lets TanStack Query be
* absent from the main application bundle, useful for including it on lazy-loaded routes only while still
* sharing a `QueryClient`. This is a small optimization; for most applications it's preferable to provide
* the `QueryClient` in the main application config, as in the examples above:
* ```ts
* export const MY_QUERY_CLIENT = new InjectionToken('', {
* factory: () => new QueryClient(),
* })
*
* // In a lazy loaded route or lazy loaded component's providers array:
* providers: [provideTanStackQuery(MY_QUERY_CLIENT)]
* ```
*/
export function provideTanStackQuery(
queryClient: QueryClient | InjectionToken<QueryClient>,
...features: Array<QueryFeatures>
): Array<Provider> {
return [
provideQueryClient(queryClient),
features.map((feature) => feature.ɵproviders),
]
}
/**
* Sets up providers necessary to enable TanStack Query functionality for Angular applications.
*
* Allows configuring a `QueryClient`.
* @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
* @param queryClient - A `QueryClient` instance.
* @returns A set of providers to set up TanStack Query.
* @deprecated Use `provideTanStackQuery` instead.
*/
export function provideAngularQuery(queryClient: QueryClient): Array<Provider> {
return provideTanStackQuery(queryClient)
}
const queryFeatures = ['Devtools', 'PersistQueryClient'] as const
type QueryFeatureKind = (typeof queryFeatures)[number]
/**
* Helper type to represent a Query feature.
*/
export interface QueryFeature<TFeatureKind extends QueryFeatureKind> {
ɵkind: TFeatureKind
ɵproviders: Array<Provider>
}
/**
* Helper function to create an object that represents a Query feature.
* @param kind - The kind of feature, e.g. `'Devtools'`.
* @param providers - The Angular providers this feature contributes to `provideTanStackQuery`.
* @returns A Query feature.
*/
export function queryFeature<TFeatureKind extends QueryFeatureKind>(
kind: TFeatureKind,
providers: Array<Provider>,
): QueryFeature<TFeatureKind> {
return { ɵkind: kind, ɵproviders: providers }
}
/**
* A type alias that represents a feature which enables developer tools.
* The type is used to describe the return value of the `withDevtools` function.
* @see {@link withDevtools}
*/
export type DevtoolsFeature = QueryFeature<'Devtools'>
/**
* A type alias that represents a feature which enables persistence.
* The type is used to describe the return value of the `withPersistQueryClient` function.
*/
export type PersistQueryClientFeature = QueryFeature<'PersistQueryClient'>
/**
* A type alias that represents all Query features available for use with `provideTanStackQuery`.
* Features can be enabled by adding special functions to the `provideTanStackQuery` call.
* See documentation for each symbol to find corresponding function name. See also `provideTanStackQuery`
* documentation on how to use those functions.
* @see {@link provideTanStackQuery}
*/
export type QueryFeatures = DevtoolsFeature | PersistQueryClientFeature

View File

@@ -0,0 +1,293 @@
import type {
DefaultError,
InitialDataFunction,
NonUndefinedGuard,
OmitKeyof,
QueryFunction,
QueryKey,
QueryKeyWithDataTag,
SkipToken,
} from '@tanstack/query-core'
import type { CreateQueryOptions } from './types'
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set — `data` may be
* `undefined` while the query is `pending`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
export type UndefinedInitialDataOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData?:
| undefined
| InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
| NonUndefinedGuard<TQueryFnData>
}
/**
* The options accepted by the `queryOptions` overload selected when no `initialData` is set and `queryFn` is
* not `skipToken` — same as {@link UndefinedInitialDataOptions}, but `queryFn` may not be `skipToken`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
export type UnusedSkipTokenOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = OmitKeyof<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryFn'
> & {
/**
* `skipToken` is not allowed as a value here — this overload is selected when no `initialData` is set. If
* you don't intend to run the query yet, set `enabled: false` — omitting `queryFn` alone still triggers a
* fetch that fails with "Missing queryFn" unless `enabled` is `false` or a default query function has been
* defined. A default query function only supplies `queryFn`; it doesn't defer the fetch on its own.
*/
queryFn?: Exclude<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>['queryFn'],
SkipToken | undefined
>
}
/**
* The options accepted by the `queryOptions` overload selected when `initialData` is set — `data` is never
* `undefined` (unless a `select` changes `TData` to include `undefined`).
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs.
* @template TQueryKey - The type of your `queryKey`.
*/
export type DefinedInitialDataOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = Omit<
CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
'queryFn'
> & {
/**
* If set, this value will be used as the initial data for the query cache (as long as the query hasn't been
* created or cached yet). If set to a function, the function will be called **once** during the shared/root
* query initialization, and be expected to synchronously return the initial data. Initial data is
* considered stale by default unless a `staleTime` has been set. `initialData` **is persisted** to the
* cache.
*/
initialData:
| NonUndefinedGuard<TQueryFnData>
| (() => NonUndefinedGuard<TQueryFnData>)
/**
* Optional here, but omitting it is only safe when no fetch will be attempted — for example with
* `enabled: false`, or when a default query function has been defined. Otherwise, an enabled query with no
* `queryFn` still tries to fetch and fails with a "Missing queryFn" error; `initialData` does not prevent this.
*/
queryFn?: QueryFunction<TQueryFnData, TQueryKey>
}
/**
* You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
* can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is
* required and is the query key to generate options for.
*
* This overload is selected when `initialData` is set, so the resulting `data` is never `undefined` (unless
* a `select` changes `TData` to include `undefined`).
*
* @see {@link injectQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link DefinedInitialDataOptions} to use — everything you can pass to `injectQuery`,
* with `initialData` set.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* ```angular-ts
* import { queryOptions, injectQuery } from '@tanstack/angular-query-experimental'
*
* export const postsOptions = queryOptions({
* queryKey: ['posts'],
* queryFn: fetchPosts,
* initialData: [],
* })
*
* @Component({
* selector: 'posts',
* template: `
* <!-- `postsQuery.data()` is never `undefined`, thanks to `initialData` — even if a refetch
* fails, so the list stays visible alongside the error. -->
* @if (postsQuery.isError()) {
* <span>Error: {{ postsQuery.error()?.message }}</span>
* }
* <ul>
* @for (post of postsQuery.data(); track post.id) {
* <li>{{ post.title }}</li>
* }
* </ul>
* `,
* })
* export class Posts {
* readonly postsQuery = injectQuery(() => postsOptions)
* }
* ```
*/
export function queryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
): DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
/**
* You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
* can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is
* required and is the query key to generate options for.
*
* @see {@link injectQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UnusedSkipTokenOptions} to use — everything you can pass to `injectQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```angular-ts
* import { queryOptions, injectQuery } from '@tanstack/angular-query-experimental'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* @Component({
* selector: 'post',
* template: `
* @if (postQuery.isPending()) {
* Loading...
* } @else if (postQuery.isError()) {
* <span>Error: {{ postQuery.error()?.message }}</span>
* } @else {
* <h1>{{ postQuery.data().title }}</h1>
* }
* `,
* })
* export class Post {
* readonly id = signal('1')
* readonly postQuery = injectQuery(() => postOptions(this.id()))
* }
* ```
*/
export function queryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey>,
): UnusedSkipTokenOptions<TQueryFnData, TError, TData, TQueryKey> &
QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
/**
* You can generally pass everything to `queryOptions` that you can also pass to `injectQuery`. These options
* can be shared across functions and imperative APIs such as `queryClient.fetchQuery`. `options.queryKey` is
* required and is the query key to generate options for.
*
* @see {@link injectQuery} to run a query with these options.
* @see [The Query Options API](https://tkdodo.eu/blog/the-query-options-api) for more on this pattern.
* @param options - The {@link UndefinedInitialDataOptions} to use — everything you can pass to `injectQuery`.
* @returns The same options object, typed so that `queryKey` carries the inferred data type.
* @remarks This is the only overload that accepts `queryFn: skipToken`, shown below.
*
* @example
* A parameterized factory, so the same options object can be reused per `id`:
* ```angular-ts
* import { queryOptions, injectQuery } from '@tanstack/angular-query-experimental'
*
* export const postOptions = (id: string) =>
* queryOptions({
* queryKey: ['post', id],
* queryFn: () => fetchPost(id),
* })
*
* @Component({
* selector: 'post',
* template: `
* @if (postQuery.isPending()) {
* Loading...
* } @else if (postQuery.isError()) {
* <span>Error: {{ postQuery.error()?.message }}</span>
* } @else {
* <h1>{{ postQuery.data().title }}</h1>
* }
* `,
* })
* export class Post {
* readonly id = signal('1')
* readonly postQuery = injectQuery(() => postOptions(this.id()))
* }
* ```
*
* @example
* A factory that disables the query, type safe, until `postId` is set:
* ```angular-ts
* import { queryOptions, skipToken, injectQuery } from '@tanstack/angular-query-experimental'
*
* export const postOptions = (postId: number | undefined) =>
* queryOptions({
* queryKey: ['post', postId],
* queryFn: postId != null ? () => fetchPost(postId) : skipToken,
* })
*
* @Component({
* selector: 'post',
* template: `
* @if (postId() == null) {
* Select a post
* } @else if (postQuery.isPending()) {
* Loading...
* } @else if (postQuery.isError()) {
* <span>Error: {{ postQuery.error()?.message }}</span>
* } @else {
* <h1>{{ postQuery.data().title }}</h1>
* }
* `,
* })
* export class Post {
* readonly postId = signal<number | undefined>(undefined)
* readonly postQuery = injectQuery(() => postOptions(this.postId()))
* }
* ```
*/
export function queryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
>(
options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
): UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey> &
QueryKeyWithDataTag<TQueryKey, TQueryFnData, TError>
export function queryOptions(options: unknown) {
return options
}

View File

@@ -0,0 +1,46 @@
import { computed, untracked } from '@angular/core'
import type { Signal } from '@angular/core'
export type MapToSignals<T> = {
[K in keyof T]: T[K] extends Function ? T[K] : Signal<T[K]>
}
/**
* Exposes fields of an object passed via an Angular `Signal` as `Computed` signals.
* Functions on the object are passed through as-is.
* @param inputSignal - `Signal` that must return an object.
* @returns A proxy object with the same fields as the input object, but with each field wrapped in a `Computed` signal.
*/
export function signalProxy<TInput extends Record<string | symbol, any>>(
inputSignal: Signal<TInput>,
) {
const internalState = {} as MapToSignals<TInput>
return new Proxy<MapToSignals<TInput>>(internalState, {
get(target, prop) {
// first check if we have it in our internal state and return it
const computedField = target[prop]
if (computedField) return computedField
// then, check if it's a function on the resultState and return it
const targetField = untracked(inputSignal)[prop]
if (typeof targetField === 'function') return targetField
// finally, create a computed field, store it and return it
// @ts-expect-error
return (target[prop] = computed(() => inputSignal()[prop]))
},
has(_, prop) {
return !!untracked(inputSignal)[prop]
},
ownKeys() {
return Reflect.ownKeys(untracked(inputSignal))
},
getOwnPropertyDescriptor() {
return {
enumerable: true,
configurable: true,
}
},
})
}

View File

@@ -0,0 +1,429 @@
/* istanbul ignore file */
import type {
DefaultError,
DefinedInfiniteQueryObserverResult,
DefinedQueryObserverResult,
InfiniteQueryObserverOptions,
InfiniteQueryObserverResult,
MutateFunction,
MutationObserverOptions,
MutationObserverResult,
OmitKeyof,
Override,
QueryKey,
QueryObserverOptions,
QueryObserverResult,
} from '@tanstack/query-core'
import type { Signal } from '@angular/core'
import type { MapToSignals } from './signal-proxy'
/**
* The options shared across `angular-query-experimental`'s query functions. Extends
* {@link QueryObserverOptions} from `@tanstack/query-core` as-is — unlike `react-query`,
* `angular-query-experimental` has no extra framework-specific option here.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryData - The type of the data actually held in the query cache — the input to `select` and
* `placeholderData`. Defaults to, and is usually the same as, `TQueryFnData`.
* @template TQueryKey - The type of your `queryKey`.
*/
export interface CreateBaseQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> extends QueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
> {}
/**
* The options accepted by `injectQuery`. Same as {@link CreateBaseQueryOptions}, minus `suspense` — which
* `angular-query-experimental` doesn't support, unlike `react-query`.
*
* @template TQueryFnData - The type your `queryFn` resolves to.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no
* `select` is used.
* @template TQueryKey - The type of your `queryKey`.
*/
export interface CreateQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> extends OmitKeyof<
CreateBaseQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>,
'suspense'
> {}
type CreateStatusBasedQueryResult<
TStatus extends QueryObserverResult['status'],
TData = unknown,
TError = DefaultError,
> = Extract<QueryObserverResult<TData, TError>, { status: TStatus }>
/**
* The `isSuccess`/`isError`/`isPending` methods on a query result. Unlike `react-query`'s derived booleans,
* these are type-guard methods you call — `if (query.isSuccess())` — so that `query.data` narrows away
* `undefined` inside the branch, the same way `status` narrowing works on the plain object `react-query`
* returns.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export interface BaseQueryNarrowing<TData = unknown, TError = DefaultError> {
isSuccess: (
this: CreateBaseQueryResult<TData, TError>,
) => this is CreateBaseQueryResult<
TData,
TError,
CreateStatusBasedQueryResult<'success', TData, TError>
>
isError: (
this: CreateBaseQueryResult<TData, TError>,
) => this is CreateBaseQueryResult<
TData,
TError,
CreateStatusBasedQueryResult<'error', TData, TError>
>
isPending: (
this: CreateBaseQueryResult<TData, TError>,
) => this is CreateBaseQueryResult<
TData,
TError,
CreateStatusBasedQueryResult<'pending', TData, TError>
>
}
/**
* The options accepted by `injectInfiniteQuery`. Same as {@link CreateBaseQueryOptions}, minus `suspense` —
* which `angular-query-experimental` doesn't support, unlike `react-query` — extends
* {@link InfiniteQueryObserverOptions} from `@tanstack/query-core` for the infinite-query-specific options
* (`getNextPageParam`, `initialPageParam`, etc.).
*
* @template TQueryFnData - The type of a single page, as your `queryFn` resolves it.
* @template TError - The type of errors your `queryFn` may throw.
* @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` here, though
* `injectInfiniteQuery` itself defaults it to `InfiniteData<TQueryFnData>` — the shape `data` actually has
* when no `select` is used.
* @template TQueryKey - The type of your `queryKey`.
* @template TPageParam - The type of the parameter passed to `queryFn` to fetch a given page.
*/
export interface CreateInfiniteQueryOptions<
TQueryFnData = unknown,
TError = DefaultError,
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
TPageParam = unknown,
> extends OmitKeyof<
InfiniteQueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryKey,
TPageParam
>,
'suspense'
> {}
/**
* The result of `injectQuery` when `initialData` isn't set — `data` may be `undefined` while the query is
* `pending`. Same shape as {@link QueryObserverResult} from `@tanstack/query-core`, but value fields (like
* `data`, `error`, `status`) are exposed as a `Signal` — read them with `query.data()`, not `query.data` —
* while function fields (like `refetch`) are called directly, unchanged. `isSuccess`/`isError`/`isPending`
* are {@link BaseQueryNarrowing} type-guard methods rather than plain booleans.
* `injectInfiniteQuery` returns {@link CreateInfiniteQueryResult} instead.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type CreateBaseQueryResult<
TData = unknown,
TError = DefaultError,
TState = QueryObserverResult<TData, TError>,
> = BaseQueryNarrowing<TData, TError> &
MapToSignals<OmitKeyof<TState, keyof BaseQueryNarrowing, 'safely'>>
/**
* The result of `injectQuery`. Same as {@link CreateBaseQueryResult}.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type CreateQueryResult<
TData = unknown,
TError = DefaultError,
> = CreateBaseQueryResult<TData, TError>
/**
* The result of `injectQuery` when `initialData` is set — `data` is never `undefined`. Same shape as
* {@link DefinedQueryObserverResult} from `@tanstack/query-core`, but value fields are exposed as a
* `Signal` while function fields are called directly, unchanged.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type DefinedCreateQueryResult<
TData = unknown,
TError = DefaultError,
TState = DefinedQueryObserverResult<TData, TError>,
> = BaseQueryNarrowing<TData, TError> &
MapToSignals<OmitKeyof<TState, keyof BaseQueryNarrowing, 'safely'>>
/**
* The result of `injectInfiniteQuery` when `initialData` isn't set — `data` may be `undefined` while the
* query is `pending`. Same shape as {@link InfiniteQueryObserverResult} from `@tanstack/query-core`, but
* value fields are exposed as a `Signal` while function fields (like `fetchNextPage`) are called directly,
* unchanged.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type CreateInfiniteQueryResult<
TData = unknown,
TError = DefaultError,
> = BaseQueryNarrowing<TData, TError> &
MapToSignals<InfiniteQueryObserverResult<TData, TError>>
/**
* The result of `injectInfiniteQuery` when `initialData` is set — `data` is never `undefined`. Same shape as
* {@link DefinedInfiniteQueryObserverResult} from `@tanstack/query-core`, but value fields are exposed as a
* `Signal` while function fields are called directly, unchanged.
*
* @template TData - The type `data` ends up as after `select` runs.
* @template TError - The type of errors your `queryFn` may throw.
*/
export type DefinedCreateInfiniteQueryResult<
TData = unknown,
TError = DefaultError,
TDefinedInfiniteQueryObserver = DefinedInfiniteQueryObserverResult<
TData,
TError
>,
> = MapToSignals<TDefinedInfiniteQueryObserver>
/**
* The options accepted by `injectMutation`. Same as {@link MutationObserverOptions} from
* `@tanstack/query-core`, minus the internal `_defaulted` flag.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export interface CreateMutationOptions<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
> extends OmitKeyof<
MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>,
'_defaulted'
> {}
/**
* The type of `mutate`, as returned by `injectMutation`. Forwards the variables (and an optional per-call
* `onSuccess`/`onError`/`onSettled`) to the underlying `mutate` call. Fire-and-forget — errors are surfaced
* through the mutation result, not thrown.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type CreateMutateFunction<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
> = (
...args: Parameters<
MutateFunction<TData, TError, TVariables, TOnMutateResult>
>
) => void
/**
* The type of `mutateAsync`, as returned by `injectMutation`. Similar to {@link CreateMutateFunction}, but
* returns a promise which can be awaited.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type CreateMutateAsyncFunction<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
> = MutateFunction<TData, TError, TVariables, TOnMutateResult>
/**
* The pre-`Signal` shape {@link CreateMutationResult} is built from — not what `injectMutation` actually
* returns. Same as {@link MutationObserverResult} from `@tanstack/query-core`, with `mutate` narrowed to the
* fire-and-forget {@link CreateMutateFunction} signature, plus the added `mutateAsync`.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type CreateBaseMutationResult<
TData = unknown,
TError = DefaultError,
TVariables = unknown,
TOnMutateResult = unknown,
> = Override<
MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,
{ mutate: CreateMutateFunction<TData, TError, TVariables, TOnMutateResult> }
> & {
/**
* Similar to `mutate`, but returns a promise which can be awaited.
*/
mutateAsync: CreateMutateAsyncFunction<
TData,
TError,
TVariables,
TOnMutateResult
>
}
type CreateStatusBasedMutationResult<
TStatus extends CreateBaseMutationResult['status'],
TData = unknown,
TError = DefaultError,
TVariables = unknown,
TOnMutateResult = unknown,
> = Extract<
CreateBaseMutationResult<TData, TError, TVariables, TOnMutateResult>,
{ status: TStatus }
>
type SignalFunction<T extends () => any> = T & Signal<ReturnType<T>>
/**
* The `isSuccess`/`isError`/`isPending`/`isIdle` methods on a mutation result. Each is both a `Signal`
* (its current boolean value is read reactively without calling it) and a type-guard function you can
* call — `if (mutation.isSuccess())` — so that `mutation.data` narrows away `undefined` inside the branch.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export interface BaseMutationNarrowing<
TData = unknown,
TError = DefaultError,
TVariables = unknown,
TOnMutateResult = unknown,
> {
isSuccess: SignalFunction<
(
this: CreateMutationResult<TData, TError, TVariables, TOnMutateResult>,
) => this is CreateMutationResult<
TData,
TError,
TVariables,
TOnMutateResult,
CreateStatusBasedMutationResult<
'success',
TData,
TError,
TVariables,
TOnMutateResult
>
>
>
isError: SignalFunction<
(
this: CreateMutationResult<TData, TError, TVariables, TOnMutateResult>,
) => this is CreateMutationResult<
TData,
TError,
TVariables,
TOnMutateResult,
CreateStatusBasedMutationResult<
'error',
TData,
TError,
TVariables,
TOnMutateResult
>
>
>
isPending: SignalFunction<
(
this: CreateMutationResult<TData, TError, TVariables, TOnMutateResult>,
) => this is CreateMutationResult<
TData,
TError,
TVariables,
TOnMutateResult,
CreateStatusBasedMutationResult<
'pending',
TData,
TError,
TVariables,
TOnMutateResult
>
>
>
isIdle: SignalFunction<
(
this: CreateMutationResult<TData, TError, TVariables, TOnMutateResult>,
) => this is CreateMutationResult<
TData,
TError,
TVariables,
TOnMutateResult,
CreateStatusBasedMutationResult<
'idle',
TData,
TError,
TVariables,
TOnMutateResult
>
>
>
}
/**
* The result of `injectMutation`. Based on {@link CreateBaseMutationResult}, but value fields are exposed as
* a `Signal` — read them with `mutation.data()`, not `mutation.data` — while function fields (`mutate`,
* `mutateAsync`, `reset`) are called directly, unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are
* {@link BaseMutationNarrowing} type-guard methods rather than plain booleans.
*
* @template TData - The type your mutation function resolves to.
* @template TError - The type of errors your mutation function may throw.
* @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`.
* @template TOnMutateResult - The type returned by `onMutate`, passed to `onSuccess`/`onError`/`onSettled` as
* their `onMutateResult` parameter — useful for optimistic-update rollback data.
*/
export type CreateMutationResult<
TData = unknown,
TError = DefaultError,
TVariables = unknown,
TOnMutateResult = unknown,
TState = CreateStatusBasedMutationResult<
CreateBaseMutationResult['status'],
TData,
TError,
TVariables,
TOnMutateResult
>,
> = BaseMutationNarrowing<TData, TError, TVariables, TOnMutateResult> &
MapToSignals<OmitKeyof<TState, keyof BaseMutationNarrowing, 'safely'>>

View File

@@ -0,0 +1,8 @@
import '@testing-library/jest-dom/vitest'
import { getTestBed } from '@angular/core/testing'
import {
BrowserTestingModule,
platformBrowserTesting,
} from '@angular/platform-browser/testing'
getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting())

View File

@@ -0,0 +1,26 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist-ts",
"rootDir": ".",
"noFallthroughCasesInSwitch": true,
"useDefineForClassFields": false,
"target": "ES2022"
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictStandalone": true,
"strictTemplates": true
},
"include": [
"src",
"scripts",
"test-setup.ts",
"*.config.ts",
"*.config.js",
"package.json"
],
"references": [{ "path": "../query-devtools" }]
}

View File

@@ -0,0 +1,15 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"incremental": false,
"composite": false,
"rootDir": "../../",
"customConditions": null,
// vite-plugin-dts must not depend on a generated query-core build.
"paths": {
"@tanstack/query-core": ["../query-core/src/index.ts"]
}
},
"include": ["src"],
"exclude": ["src/__tests__"]
}

View File

@@ -0,0 +1,131 @@
import { defineConfig, mergeConfig } from 'vitest/config'
import { externalizeDeps } from 'vite-plugin-externalize-deps'
import tsconfigPaths from 'vite-tsconfig-paths'
import dts from 'vite-plugin-dts'
import packageJson from './package.json'
import type { Options } from '@tanstack/vite-config'
function ensureImportFileExtension({
content,
extension,
}: {
content: string
extension: string
}) {
// replace e.g. `import { foo } from './foo'` with `import { foo } from './foo.js'`
content = content.replace(
/(im|ex)port\s[\w{}/*\s,]+from\s['"](?:\.\.?\/)+?[^.'"]+(?=['"];?)/gm,
`$&.${extension}`,
)
// replace e.g. `import('./foo')` with `import('./foo.js')`
content = content.replace(
/import\(['"](?:\.\.?\/)+?[^.'"]+(?=['"];?)/gm,
`$&.${extension}`,
)
return content
}
const config = defineConfig({
// fix from https://github.com/vitest-dev/vitest/issues/6992#issuecomment-2509408660
resolve: {
conditions: ['@tanstack/custom-condition'],
},
environments: {
ssr: {
resolve: {
conditions: ['@tanstack/custom-condition'],
},
},
},
test: {
name: packageJson.name,
dir: './src',
watch: false,
environment: 'jsdom',
setupFiles: ['test-setup.ts'],
coverage: {
enabled: !!process.env.CI,
provider: 'istanbul',
include: ['src/**/*'],
exclude: ['src/__tests__/**'],
},
typecheck: { enabled: true },
globals: true,
restoreMocks: true,
},
})
// copy from @tanstack/config/vite with changes:
// - build - lib - fileName: [name.mjs]
// - rollup - output - preserveModulesRoot: src
export const tanstackViteConfig = (options: Options) => {
const outDir = options.outDir ?? 'dist'
const cjs = options.cjs ?? true
return defineConfig({
plugins: [
externalizeDeps({ include: options.externalDeps ?? [] }),
tsconfigPaths({
projects: options.tsconfigPath ? [options.tsconfigPath] : undefined,
}),
dts({
outDir,
entryRoot: options.srcDir,
include: options.srcDir,
exclude: options.exclude,
tsconfigPath: options.tsconfigPath,
compilerOptions: {
module: 99, // ESNext
declarationMap: false,
},
beforeWriteFile: (filePath, content) => {
return {
filePath,
content: ensureImportFileExtension({ content, extension: 'js' }),
}
},
afterDiagnostic: (diagnostics) => {
if (diagnostics.length > 0) {
console.error('Please fix the above type errors')
process.exit(1)
}
},
}),
],
build: {
outDir,
minify: false,
sourcemap: true,
lib: {
entry: options.entry,
formats: cjs ? ['es', 'cjs'] : ['es'],
fileName: () => '[name].mjs',
},
rollupOptions: {
output: {
preserveModules: true,
preserveModulesRoot: 'src',
},
},
},
})
}
export default mergeConfig(
config,
tanstackViteConfig({
cjs: false,
entry: [
'./src/index.ts',
'./src/inject-queries-experimental/index.ts',
'./src/devtools-panel/index.ts',
'./src/devtools-panel/stub.ts',
'./src/devtools/index.ts',
'./src/devtools/stub.ts',
],
exclude: ['src/__tests__'],
srcDir: './src',
tsconfigPath: 'tsconfig.prod.json',
}),
)