@tanstack/angular-query 0.0.0 → 5.0.0-rc.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +120 -36
- package/hydration-state-key.d.ts +4 -0
- package/hydration-state-key.mjs +14 -0
- package/hydration-state-key.mjs.map +1 -0
- package/index.d.ts +22 -0
- package/index.mjs +32 -0
- package/index.mjs.map +1 -0
- package/infinite-query-options.d.ts +216 -0
- package/infinite-query-options.mjs +7 -0
- package/infinite-query-options.mjs.map +1 -0
- package/inject-base-query.d.ts +5 -0
- package/inject-base-query.mjs +64 -0
- package/inject-base-query.mjs.map +1 -0
- package/inject-infinite-query.d.ts +67 -0
- package/inject-infinite-query.mjs +38 -0
- package/inject-infinite-query.mjs.map +1 -0
- package/inject-is-fetching.d.ts +11 -0
- package/inject-is-fetching.mjs +18 -0
- package/inject-is-fetching.mjs.map +1 -0
- package/inject-is-mutating.d.ts +11 -0
- package/inject-is-mutating.mjs +18 -0
- package/inject-is-mutating.mjs.map +1 -0
- package/inject-is-restoring.d.ts +13 -0
- package/inject-is-restoring.mjs +21 -0
- package/inject-is-restoring.mjs.map +1 -0
- package/inject-mutation-state.d.ts +16 -0
- package/inject-mutation-state.mjs +28 -0
- package/inject-mutation-state.mjs.map +1 -0
- package/inject-mutation.d.ts +32 -0
- package/inject-mutation.mjs +72 -0
- package/inject-mutation.mjs.map +1 -0
- package/inject-queries.d.ts +35 -0
- package/inject-queries.mjs +120 -0
- package/inject-queries.mjs.map +1 -0
- package/inject-queries.types.d.ts +109 -0
- package/inject-query.d.ts +127 -0
- package/inject-query.mjs +20 -0
- package/inject-query.mjs.map +1 -0
- package/internal.d.ts +8 -0
- package/internal.mjs +8 -0
- package/internal.mjs.map +1 -0
- package/mutation-options.d.ts +84 -0
- package/mutation-options.mjs +7 -0
- package/mutation-options.mjs.map +1 -0
- package/package.json +52 -4
- package/providers.d.ts +83 -0
- package/providers.mjs +89 -0
- package/providers.mjs.map +1 -0
- package/query-options.d.ts +208 -0
- package/query-options.mjs +7 -0
- package/query-options.mjs.map +1 -0
- package/query-resource.d.ts +36 -0
- package/query-resource.mjs +70 -0
- package/query-resource.mjs.map +1 -0
- package/schematics/collection.json +10 -0
- package/schematics/ng-add/index.js +96 -0
- package/schematics/ng-add/schema.js +2 -0
- package/schematics/ng-add/schema.json +17 -0
- package/schematics/package.json +3 -0
- package/types.d.ts +164 -0
- package/utils/inject-external-store.d.ts +33 -0
- package/utils/inject-external-store.mjs +41 -0
- package/utils/inject-external-store.mjs.map +1 -0
- package/utils/inject-pending-tasks-lifecycle.d.ts +6 -0
- package/utils/inject-pending-tasks-lifecycle.mjs +31 -0
- package/utils/inject-pending-tasks-lifecycle.mjs.map +1 -0
- package/utils/inject-query-zone.d.ts +2 -0
- package/utils/inject-query-zone.mjs +9 -0
- package/utils/inject-query-zone.mjs.map +1 -0
- package/utils/resource-types.d.ts +8 -0
- package/utils/result-fields.d.ts +80 -0
- package/utils/result-fields.mjs +65 -0
- package/utils/result-fields.mjs.map +1 -0
- package/utils/signal-proxy.d.ts +20 -0
- package/utils/signal-proxy.mjs +12 -0
- package/utils/signal-proxy.mjs.map +1 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { DefaultError, DefinedQueryObserverResult, OmitKeyof, QueriesPlaceholderDataFunction, QueryFunction, QueryKey, QueryObserverResult, dataTagErrorSymbol } from '@tanstack/query-core';
|
|
2
|
+
import { CreateQueryOptions, CreateQueryResult, DefinedCreateQueryResult } from './types.js';
|
|
3
|
+
type QueryObserverOptionsForCreateQueries<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = OmitKeyof<CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'placeholderData'> & {
|
|
4
|
+
placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>;
|
|
5
|
+
};
|
|
6
|
+
type QueryError<T> = T extends {
|
|
7
|
+
queryKey: {
|
|
8
|
+
[dataTagErrorSymbol]: infer TError;
|
|
9
|
+
};
|
|
10
|
+
} ? TError : T extends CreateQueryOptions<any, infer TError, any, any> ? unknown extends TError ? DefaultError : TError : DefaultError;
|
|
11
|
+
type MAXIMUM_DEPTH = 20;
|
|
12
|
+
type SkipTokenForCreateQueries = symbol;
|
|
13
|
+
type GetCreateQueryOptionsForCreateQueries<T> = T extends {
|
|
14
|
+
queryFnData: infer TQueryFnData;
|
|
15
|
+
error?: infer TError;
|
|
16
|
+
data: infer TData;
|
|
17
|
+
} ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData> : T extends {
|
|
18
|
+
queryFnData: infer TQueryFnData;
|
|
19
|
+
error?: infer TError;
|
|
20
|
+
} ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError> : T extends {
|
|
21
|
+
data: infer TData;
|
|
22
|
+
error?: infer TError;
|
|
23
|
+
} ? QueryObserverOptionsForCreateQueries<unknown, TError, TData> : T extends [infer TQueryFnData, infer TError, infer TData] ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData> : T extends [infer TQueryFnData, infer TError] ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError> : T extends [infer TQueryFnData] ? QueryObserverOptionsForCreateQueries<TQueryFnData> : T extends {
|
|
24
|
+
queryFn?: QueryFunction<infer TQueryFnData, infer TQueryKey> | SkipTokenForCreateQueries;
|
|
25
|
+
select?: (data: any) => infer TData;
|
|
26
|
+
} ? QueryObserverOptionsForCreateQueries<TQueryFnData, QueryError<T>, unknown extends TData ? TQueryFnData : TData, TQueryKey> : QueryObserverOptionsForCreateQueries;
|
|
27
|
+
type GenericGetDefinedOrUndefinedQueryResult<T, TData, TUndefined, TDefined> = T extends {
|
|
28
|
+
initialData?: infer TInitialData;
|
|
29
|
+
} ? unknown extends TInitialData ? TUndefined : TInitialData extends TData ? TDefined : TInitialData extends () => infer TInitialDataResult ? unknown extends TInitialDataResult ? TUndefined : TInitialDataResult extends TData ? TDefined : TUndefined : TUndefined : TUndefined;
|
|
30
|
+
type InferDataAndError<T> = T extends {
|
|
31
|
+
queryFnData: any;
|
|
32
|
+
error?: infer TError;
|
|
33
|
+
data: infer TData;
|
|
34
|
+
} ? {
|
|
35
|
+
data: TData;
|
|
36
|
+
error: TError;
|
|
37
|
+
} : T extends {
|
|
38
|
+
queryFnData: infer TQueryFnData;
|
|
39
|
+
error?: infer TError;
|
|
40
|
+
} ? {
|
|
41
|
+
data: TQueryFnData;
|
|
42
|
+
error: TError;
|
|
43
|
+
} : T extends {
|
|
44
|
+
data: infer TData;
|
|
45
|
+
error?: infer TError;
|
|
46
|
+
} ? {
|
|
47
|
+
data: TData;
|
|
48
|
+
error: TError;
|
|
49
|
+
} : T extends [any, infer TError, infer TData] ? {
|
|
50
|
+
data: TData;
|
|
51
|
+
error: TError;
|
|
52
|
+
} : T extends [infer TQueryFnData, infer TError] ? {
|
|
53
|
+
data: TQueryFnData;
|
|
54
|
+
error: TError;
|
|
55
|
+
} : T extends [infer TQueryFnData] ? {
|
|
56
|
+
data: TQueryFnData;
|
|
57
|
+
error: unknown;
|
|
58
|
+
} : T extends {
|
|
59
|
+
queryFn?: QueryFunction<infer TQueryFnData, any> | SkipTokenForCreateQueries;
|
|
60
|
+
select?: (data: any) => infer TData;
|
|
61
|
+
} ? {
|
|
62
|
+
data: unknown extends TData ? TQueryFnData : TData;
|
|
63
|
+
error: QueryError<T>;
|
|
64
|
+
} : {
|
|
65
|
+
data: unknown;
|
|
66
|
+
error: DefaultError;
|
|
67
|
+
};
|
|
68
|
+
type GetCreateQueryResult<T> = GenericGetDefinedOrUndefinedQueryResult<T, InferDataAndError<T>['data'], CreateQueryResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>, DefinedCreateQueryResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>>;
|
|
69
|
+
type GetQueryObserverResult<T> = GenericGetDefinedOrUndefinedQueryResult<T, InferDataAndError<T>['data'], QueryObserverResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>, DefinedQueryObserverResult<InferDataAndError<T>['data'], InferDataAndError<T>['error']>>;
|
|
70
|
+
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<[
|
|
71
|
+
...Tails
|
|
72
|
+
], [
|
|
73
|
+
...TResults,
|
|
74
|
+
GetCreateQueryOptionsForCreateQueries<Head>
|
|
75
|
+
], [
|
|
76
|
+
...TDepth,
|
|
77
|
+
1
|
|
78
|
+
]> : ReadonlyArray<unknown> extends T ? T : T extends Array<QueryObserverOptionsForCreateQueries<infer TQueryFnData, infer TError, infer TData, infer TQueryKey>> ? Array<QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData, TQueryKey>> : Array<QueryObserverOptionsForCreateQueries>;
|
|
79
|
+
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<[
|
|
80
|
+
...Tails
|
|
81
|
+
], [
|
|
82
|
+
...TResults,
|
|
83
|
+
GetCreateQueryResult<Head>
|
|
84
|
+
], [
|
|
85
|
+
...TDepth,
|
|
86
|
+
1
|
|
87
|
+
]> : {
|
|
88
|
+
[K in keyof T]: GetCreateQueryResult<T[K]>;
|
|
89
|
+
};
|
|
90
|
+
type RawQueriesResults<T extends Array<any>, TResults extends Array<any> = [], TDepth extends ReadonlyArray<number> = []> = TDepth['length'] extends MAXIMUM_DEPTH ? Array<QueryObserverResult> : T extends [] ? [] : T extends [infer Head] ? [...TResults, GetQueryObserverResult<Head>] : T extends [infer Head, ...infer Tails] ? RawQueriesResults<[
|
|
91
|
+
...Tails
|
|
92
|
+
], [
|
|
93
|
+
...TResults,
|
|
94
|
+
GetQueryObserverResult<Head>
|
|
95
|
+
], [
|
|
96
|
+
...TDepth,
|
|
97
|
+
1
|
|
98
|
+
]> : {
|
|
99
|
+
[K in keyof T]: GetQueryObserverResult<T[K]>;
|
|
100
|
+
};
|
|
101
|
+
export interface InjectQueriesOptions<T extends Array<any>, TCombinedResult = QueriesResults<T>> {
|
|
102
|
+
queries: readonly [...QueriesOptions<T>] | readonly [
|
|
103
|
+
...{
|
|
104
|
+
[K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]>;
|
|
105
|
+
}
|
|
106
|
+
];
|
|
107
|
+
combine?: (result: RawQueriesResults<T>) => TCombinedResult;
|
|
108
|
+
}
|
|
109
|
+
export {};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { DefaultError, QueryKey } from '@tanstack/query-core';
|
|
2
|
+
import { CreateQueryOptions, CreateQueryResult, DefinedCreateQueryResult } from './types.js';
|
|
3
|
+
import { DefinedInitialDataOptions, UndefinedInitialDataOptions } from './query-options.js';
|
|
4
|
+
/**
|
|
5
|
+
* This overload is selected when `initialData` is set on the options returned by `optionsFn`, so the
|
|
6
|
+
* resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).
|
|
7
|
+
*
|
|
8
|
+
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
|
|
9
|
+
* @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
|
|
10
|
+
* `queryClient.query`.
|
|
11
|
+
* @param optionsFn - A function returning the {@link DefinedInitialDataOptions} to use — everything you
|
|
12
|
+
* can pass to `injectQuery`, with `initialData` set. Similar to `computed` from Angular, this function runs
|
|
13
|
+
* in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
|
|
14
|
+
* @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to
|
|
15
|
+
* include `undefined`).
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```angular-ts
|
|
19
|
+
* @Component({
|
|
20
|
+
* selector: 'posts',
|
|
21
|
+
* template: `
|
|
22
|
+
* <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` — even if a
|
|
23
|
+
* refetch fails, so the list stays visible alongside the error. -->
|
|
24
|
+
* @if (postsQuery.isError()) {
|
|
25
|
+
* <span>Error: {{ postsQuery.error()?.message }}</span>
|
|
26
|
+
* }
|
|
27
|
+
* <ul>
|
|
28
|
+
* @for (post of postsQuery.data(); track post.id) {
|
|
29
|
+
* <li>{{ post.title }}</li>
|
|
30
|
+
* }
|
|
31
|
+
* </ul>
|
|
32
|
+
* `,
|
|
33
|
+
* })
|
|
34
|
+
* export class Posts {
|
|
35
|
+
* readonly postsQuery = injectQuery(() => ({
|
|
36
|
+
* queryKey: ['posts'],
|
|
37
|
+
* queryFn: fetchPosts,
|
|
38
|
+
* initialData: [],
|
|
39
|
+
* }))
|
|
40
|
+
* }
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export declare function injectQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(optionsFn: () => DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): DefinedCreateQueryResult<TData, TError>;
|
|
44
|
+
/**
|
|
45
|
+
* Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
|
|
46
|
+
*
|
|
47
|
+
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
|
|
48
|
+
* @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like
|
|
49
|
+
* `queryClient.query`.
|
|
50
|
+
* @param optionsFn - A function returning the {@link UndefinedInitialDataOptions} to use — everything
|
|
51
|
+
* you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive
|
|
52
|
+
* context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.
|
|
53
|
+
* @returns The query result. `status()` is `'pending'` if there is no cached data to display, `'error'` if
|
|
54
|
+
* the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/
|
|
55
|
+
* `isError` are type-guard methods for convenience.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
* ```angular-ts
|
|
59
|
+
* @Component({
|
|
60
|
+
* selector: 'posts',
|
|
61
|
+
* template: `
|
|
62
|
+
* @if (postsQuery.isPending()) {
|
|
63
|
+
* Loading...
|
|
64
|
+
* } @else if (postsQuery.isError()) {
|
|
65
|
+
* <span>Error: {{ postsQuery.error()?.message }}</span>
|
|
66
|
+
* } @else {
|
|
67
|
+
* <ul>
|
|
68
|
+
* @for (post of postsQuery.data(); track post.id) {
|
|
69
|
+
* <li>{{ post.title }}</li>
|
|
70
|
+
* }
|
|
71
|
+
* </ul>
|
|
72
|
+
* }
|
|
73
|
+
* `,
|
|
74
|
+
* })
|
|
75
|
+
* export class Posts {
|
|
76
|
+
* readonly postsQuery = injectQuery(() => ({
|
|
77
|
+
* queryKey: ['posts'],
|
|
78
|
+
* queryFn: fetchPosts,
|
|
79
|
+
* }))
|
|
80
|
+
* }
|
|
81
|
+
* ```
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In
|
|
85
|
+
* the example below, the query is automatically enabled and executed when the filter signal changes to a
|
|
86
|
+
* truthy value. When the filter signal changes back to a falsy value, the query is disabled.
|
|
87
|
+
* ```angular-ts
|
|
88
|
+
* @Component({
|
|
89
|
+
* selector: 'posts',
|
|
90
|
+
* template: `
|
|
91
|
+
* <input [ngModel]="filter()" (ngModelChange)="filter.set($event)" />
|
|
92
|
+
* @if (postsQuery.isPending()) {
|
|
93
|
+
* Loading...
|
|
94
|
+
* } @else if (postsQuery.isError()) {
|
|
95
|
+
* <span>Error: {{ postsQuery.error()?.message }}</span>
|
|
96
|
+
* } @else {
|
|
97
|
+
* <ul>
|
|
98
|
+
* @for (post of postsQuery.data(); track post.id) {
|
|
99
|
+
* <li>{{ post.title }}</li>
|
|
100
|
+
* }
|
|
101
|
+
* </ul>
|
|
102
|
+
* }
|
|
103
|
+
* `,
|
|
104
|
+
* })
|
|
105
|
+
* export class Posts {
|
|
106
|
+
* readonly filter = signal('')
|
|
107
|
+
*
|
|
108
|
+
* readonly postsQuery = injectQuery(() => ({
|
|
109
|
+
* queryKey: ['posts', this.filter()],
|
|
110
|
+
* queryFn: () => fetchPosts(this.filter()),
|
|
111
|
+
* enabled: !!this.filter(),
|
|
112
|
+
* }))
|
|
113
|
+
* }
|
|
114
|
+
* ```
|
|
115
|
+
*/
|
|
116
|
+
export declare function injectQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(optionsFn: () => UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>): CreateQueryResult<TData, TError>;
|
|
117
|
+
/**
|
|
118
|
+
* This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware
|
|
119
|
+
* overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping
|
|
120
|
+
* `injectQuery` in your own helper function that forwards caller-provided options.
|
|
121
|
+
*
|
|
122
|
+
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries
|
|
123
|
+
* @param optionsFn - A function that returns query options. Similar to `computed` from Angular, this
|
|
124
|
+
* function runs in the reactive context, so signals read inside it drive the query.
|
|
125
|
+
* @returns The query result.
|
|
126
|
+
*/
|
|
127
|
+
export declare function injectQuery<TQueryFnData = unknown, TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(optionsFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>): CreateQueryResult<TData, TError>;
|
package/inject-query.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { QueryObserver } from "@tanstack/query-core";
|
|
2
|
+
import { assertInInjectionContext, untracked } from "@angular/core";
|
|
3
|
+
import { injectQueryZone } from "./utils/inject-query-zone.mjs";
|
|
4
|
+
import { injectBaseQuery } from "./inject-base-query.mjs";
|
|
5
|
+
import { signalProxy } from "./utils/signal-proxy.mjs";
|
|
6
|
+
import { queryResultFields } from "./utils/result-fields.mjs";
|
|
7
|
+
function injectQuery(optionsFn) {
|
|
8
|
+
if (typeof ngDevMode === "undefined" || ngDevMode) {
|
|
9
|
+
assertInInjectionContext(injectQuery);
|
|
10
|
+
}
|
|
11
|
+
const outsideZone = injectQueryZone();
|
|
12
|
+
const [resultSignal, getObserver] = injectBaseQuery(optionsFn, QueryObserver);
|
|
13
|
+
return Object.assign(signalProxy(resultSignal, queryResultFields), {
|
|
14
|
+
refetch: (options) => outsideZone(() => untracked(() => getObserver().refetch(options)))
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
export {
|
|
18
|
+
injectQuery
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=inject-query.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inject-query.mjs","sources":["../src/inject-query.ts"],"sourcesContent":["import { QueryObserver } from '@tanstack/query-core'\nimport { assertInInjectionContext, untracked } from '@angular/core'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { injectBaseQuery } from './inject-base-query'\nimport { signalProxy } from './utils/signal-proxy'\nimport { queryResultFields } from './utils/result-fields'\nimport type {\n DefaultError,\n QueryKey,\n RefetchOptions,\n} from '@tanstack/query-core'\nimport type {\n CreateQueryOptions,\n CreateQueryResult,\n DefinedCreateQueryResult,\n} from './types'\nimport type {\n DefinedInitialDataOptions,\n UndefinedInitialDataOptions,\n} from './query-options'\n\n/**\n * This overload is selected when `initialData` is set on the options returned by `optionsFn`, so the\n * resulting `data` signal is never `undefined` (unless a `select` changes `TData` to include `undefined`).\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.query`.\n * @param optionsFn - A function returning the {@link DefinedInitialDataOptions} to use — everything you\n * can pass to `injectQuery`, with `initialData` set. Similar to `computed` from Angular, this function runs\n * in the reactive context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @returns The query result, typed so that `data` is never `undefined` (unless a `select` changes `TData` to\n * include `undefined`).\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <!-- `postsQuery.data()` is `Post[]`, never `undefined`, thanks to `initialData` — even if a\n * refetch fails, so the list stays visible alongside the error. -->\n * @if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * }\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * initialData: [],\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => DefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n): DefinedCreateQueryResult<TData, TError>\n\n/**\n * Injects a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @see {@link queryOptions} to share these options between `injectQuery` and imperative APIs like\n * `queryClient.query`.\n * @param optionsFn - A function returning the {@link UndefinedInitialDataOptions} to use — everything\n * you can pass to `injectQuery`. Similar to `computed` from Angular, this function runs in the reactive\n * context, so signals read inside it (in `queryKey`, `enabled`, etc.) drive the query.\n * @returns The query result. `status()` is `'pending'` if there is no cached data to display, `'error'` if\n * the last fetch attempt failed, or `'success'` if the query has data to display. `isPending`/`isSuccess`/\n * `isError` are type-guard methods for convenience.\n *\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts'],\n * queryFn: fetchPosts,\n * }))\n * }\n * ```\n *\n * @example\n * Similar to `computed` from Angular, the function passed to `injectQuery` runs in the reactive context. In\n * the example below, the query is automatically enabled and executed when the filter signal changes to a\n * truthy value. When the filter signal changes back to a falsy value, the query is disabled.\n * ```angular-ts\n * @Component({\n * selector: 'posts',\n * template: `\n * <input [ngModel]=\"filter()\" (ngModelChange)=\"filter.set($event)\" />\n * @if (postsQuery.isPending()) {\n * Loading...\n * } @else if (postsQuery.isError()) {\n * <span>Error: {{ postsQuery.error()?.message }}</span>\n * } @else {\n * <ul>\n * @for (post of postsQuery.data(); track post.id) {\n * <li>{{ post.title }}</li>\n * }\n * </ul>\n * }\n * `,\n * })\n * export class Posts {\n * readonly filter = signal('')\n *\n * readonly postsQuery = injectQuery(() => ({\n * queryKey: ['posts', this.filter()],\n * queryFn: () => fetchPosts(this.filter()),\n * enabled: !!this.filter(),\n * }))\n * }\n * ```\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => UndefinedInitialDataOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >,\n): CreateQueryResult<TData, TError>\n\n/**\n * This overload accepts the general {@link CreateQueryOptions} shape rather than the `initialData`-aware\n * overloads above, so whether `data` is defined can't be inferred from the call site — useful when wrapping\n * `injectQuery` in your own helper function that forwards caller-provided options.\n *\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/queries\n * @param optionsFn - A function that returns query options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it drive the query.\n * @returns The query result.\n */\nexport function injectQuery<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n>(\n optionsFn: () => CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n): CreateQueryResult<TData, TError>\n\nexport function injectQuery(\n optionsFn: () => CreateQueryOptions,\n): DefinedCreateQueryResult | CreateQueryResult {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectQuery)\n }\n const outsideZone = injectQueryZone()\n const [resultSignal, getObserver] = injectBaseQuery(optionsFn, QueryObserver)\n return Object.assign(signalProxy(resultSignal, queryResultFields), {\n refetch: (options?: RefetchOptions) =>\n outsideZone(() => untracked(() => getObserver().refetch(options))),\n }) as unknown as DefinedCreateQueryResult | CreateQueryResult\n}\n"],"names":[],"mappings":";;;;;;AAmLO,SAAS,YACd,WAC8C;AAC9C,MAAI,OAAO,cAAc,eAAe,WAAW;AACjD,6BAAyB,WAAW;AAAA,EACtC;AACA,QAAM,cAAc,gBAAA;AACpB,QAAM,CAAC,cAAc,WAAW,IAAI,gBAAgB,WAAW,aAAa;AAC5E,SAAO,OAAO,OAAO,YAAY,cAAc,iBAAiB,GAAG;AAAA,IACjE,SAAS,CAAC,YACR,YAAY,MAAM,UAAU,MAAM,YAAA,EAAc,QAAQ,OAAO,CAAC,CAAC;AAAA,EAAA,CACpE;AACH;"}
|
package/internal.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Internal APIs shared by the Angular Query packages.
|
|
3
|
+
*
|
|
4
|
+
* This entry point is not part of the application-facing API and may change
|
|
5
|
+
* without notice.
|
|
6
|
+
*/
|
|
7
|
+
export { getQueryFeatureProviders, queryFeature } from './providers.js';
|
|
8
|
+
export { provideIsRestoring } from './inject-is-restoring.js';
|
package/internal.mjs
ADDED
package/internal.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal.mjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { DefaultError, WithRequired } from '@tanstack/query-core';
|
|
2
|
+
import { CreateMutationOptions } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. A
|
|
5
|
+
* `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with
|
|
6
|
+
* `injectMutationState`.
|
|
7
|
+
*
|
|
8
|
+
* @see {@link injectMutation} to run the mutation these options describe.
|
|
9
|
+
* @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, with a
|
|
10
|
+
* required `mutationKey`.
|
|
11
|
+
* @returns The same options object, unchanged.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global "saving…" indicator:
|
|
15
|
+
* ```angular-ts
|
|
16
|
+
* import { mutationOptions, injectMutationState } from '@tanstack/angular-query'
|
|
17
|
+
*
|
|
18
|
+
* const createPostOptions = mutationOptions({
|
|
19
|
+
* mutationKey: ['posts', 'create'],
|
|
20
|
+
* mutationFn: createPost,
|
|
21
|
+
* })
|
|
22
|
+
*
|
|
23
|
+
* @Component({
|
|
24
|
+
* selector: 'saving-indicator',
|
|
25
|
+
* template: `
|
|
26
|
+
* @if (isCreatingPost()) {
|
|
27
|
+
* <span>Saving…</span>
|
|
28
|
+
* }
|
|
29
|
+
* `,
|
|
30
|
+
* })
|
|
31
|
+
* export class SavingIndicator {
|
|
32
|
+
* readonly #pendingCreates = injectMutationState(() => ({
|
|
33
|
+
* filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },
|
|
34
|
+
* }))
|
|
35
|
+
* readonly isCreatingPost = computed(() => this.#pendingCreates().length > 0)
|
|
36
|
+
* }
|
|
37
|
+
* ```
|
|
38
|
+
*/
|
|
39
|
+
export declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: WithRequired<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): WithRequired<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
|
|
40
|
+
/**
|
|
41
|
+
* You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. No
|
|
42
|
+
* `mutationKey` is required on this overload — use this when you don't need to target the mutation via a
|
|
43
|
+
* `mutationKey` filter later (e.g. with `injectMutationState`); it can still be observed through other
|
|
44
|
+
* filters, such as `status`.
|
|
45
|
+
*
|
|
46
|
+
* @see {@link injectMutation} to run the mutation these options describe.
|
|
47
|
+
* @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, without a
|
|
48
|
+
* `mutationKey`.
|
|
49
|
+
* @returns The same options object, unchanged.
|
|
50
|
+
* @remarks See the other overload's example for looking a mutation up via `injectMutationState`.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* Sharing options across services, so `QueriesService` stays the single place a mutation is defined:
|
|
54
|
+
* ```angular-ts
|
|
55
|
+
* import { mutationOptions, injectMutation } from '@tanstack/angular-query'
|
|
56
|
+
*
|
|
57
|
+
* @Injectable({ providedIn: 'root' })
|
|
58
|
+
* export class QueriesService {
|
|
59
|
+
* readonly #queryClient = inject(QueryClient)
|
|
60
|
+
*
|
|
61
|
+
* updatePost(id: number) {
|
|
62
|
+
* return mutationOptions({
|
|
63
|
+
* mutationFn: (post: Partial<Post>) => putPost(id, post),
|
|
64
|
+
* onSuccess: (newPost) => this.#queryClient.setQueryData(['posts', id], newPost),
|
|
65
|
+
* })
|
|
66
|
+
* }
|
|
67
|
+
* }
|
|
68
|
+
*
|
|
69
|
+
* @Component({
|
|
70
|
+
* selector: 'post',
|
|
71
|
+
* template: `<button (click)="save()">Save</button>`,
|
|
72
|
+
* })
|
|
73
|
+
* export class Post {
|
|
74
|
+
* readonly queries = inject(QueriesService)
|
|
75
|
+
* readonly id = signal(0)
|
|
76
|
+
* readonly updatePostMutation = injectMutation(() => this.queries.updatePost(this.id()))
|
|
77
|
+
*
|
|
78
|
+
* save() {
|
|
79
|
+
* this.updatePostMutation.mutate({ title: 'New Title' })
|
|
80
|
+
* }
|
|
81
|
+
* }
|
|
82
|
+
* ```
|
|
83
|
+
*/
|
|
84
|
+
export declare function mutationOptions<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(options: Omit<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>): Omit<CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>, 'mutationKey'>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mutation-options.mjs","sources":["../src/mutation-options.ts"],"sourcesContent":["import type { DefaultError, WithRequired } from '@tanstack/query-core'\nimport type { CreateMutationOptions } from './types'\n\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. A\n * `mutationKey` is required on this overload so the mutation can be looked up later, e.g. with\n * `injectMutationState`.\n *\n * @see {@link injectMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, with a\n * required `mutationKey`.\n * @returns The same options object, unchanged.\n *\n * @example\n * Looking the mutation up elsewhere via its `mutationKey`, e.g. for a global \"saving…\" indicator:\n * ```angular-ts\n * import { mutationOptions, injectMutationState } from '@tanstack/angular-query'\n *\n * const createPostOptions = mutationOptions({\n * mutationKey: ['posts', 'create'],\n * mutationFn: createPost,\n * })\n *\n * @Component({\n * selector: 'saving-indicator',\n * template: `\n * @if (isCreatingPost()) {\n * <span>Saving…</span>\n * }\n * `,\n * })\n * export class SavingIndicator {\n * readonly #pendingCreates = injectMutationState(() => ({\n * filters: { mutationKey: createPostOptions.mutationKey, status: 'pending' },\n * }))\n * readonly isCreatingPost = computed(() => this.#pendingCreates().length > 0)\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: WithRequired<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): WithRequired<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\n/**\n * You can generally pass everything to `mutationOptions` that you can also pass to `injectMutation`. No\n * `mutationKey` is required on this overload — use this when you don't need to target the mutation via a\n * `mutationKey` filter later (e.g. with `injectMutationState`); it can still be observed through other\n * filters, such as `status`.\n *\n * @see {@link injectMutation} to run the mutation these options describe.\n * @param options - The mutation options to use, identical to what you'd pass to `injectMutation`, without a\n * `mutationKey`.\n * @returns The same options object, unchanged.\n * @remarks See the other overload's example for looking a mutation up via `injectMutationState`.\n *\n * @example\n * Sharing options across services, so `QueriesService` stays the single place a mutation is defined:\n * ```angular-ts\n * import { mutationOptions, injectMutation } from '@tanstack/angular-query'\n *\n * @Injectable({ providedIn: 'root' })\n * export class QueriesService {\n * readonly #queryClient = inject(QueryClient)\n *\n * updatePost(id: number) {\n * return mutationOptions({\n * mutationFn: (post: Partial<Post>) => putPost(id, post),\n * onSuccess: (newPost) => this.#queryClient.setQueryData(['posts', id], newPost),\n * })\n * }\n * }\n *\n * @Component({\n * selector: 'post',\n * template: `<button (click)=\"save()\">Save</button>`,\n * })\n * export class Post {\n * readonly queries = inject(QueriesService)\n * readonly id = signal(0)\n * readonly updatePostMutation = injectMutation(() => this.queries.updatePost(this.id()))\n *\n * save() {\n * this.updatePostMutation.mutate({ title: 'New Title' })\n * }\n * }\n * ```\n */\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: Omit<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n >,\n): Omit<\n CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n 'mutationKey'\n>\nexport function mutationOptions<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n options: CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>,\n): CreateMutationOptions<TData, TError, TVariables, TOnMutateResult> {\n return options\n}\n"],"names":[],"mappings":"AA+GO,SAAS,gBAMd,SACmE;AACnE,SAAO;AACT;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/angular-query",
|
|
3
|
-
"version": "0.0.0",
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "5.0.0-rc.0",
|
|
4
|
+
"description": "Signals for managing, caching and syncing asynchronous and remote data in Angular",
|
|
5
|
+
"author": "Arnoud de Vries",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/TanStack/query.git",
|
|
10
|
+
"directory": "packages/angular-query"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://tanstack.com/query",
|
|
13
|
+
"funding": {
|
|
14
|
+
"type": "github",
|
|
15
|
+
"url": "https://github.com/sponsors/tannerlinsley"
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"angular query",
|
|
19
|
+
"angular",
|
|
20
|
+
"cache",
|
|
21
|
+
"performance",
|
|
22
|
+
"reactive",
|
|
23
|
+
"signals",
|
|
24
|
+
"state management",
|
|
25
|
+
"state",
|
|
26
|
+
"tanstack"
|
|
27
|
+
],
|
|
28
|
+
"type": "module",
|
|
29
|
+
"schematics": "./schematics/collection.json",
|
|
30
|
+
"ng-add": {
|
|
31
|
+
"save": "dependencies"
|
|
32
|
+
},
|
|
33
|
+
"types": "./index.d.ts",
|
|
34
|
+
"module": "./index.mjs",
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./index.d.ts",
|
|
38
|
+
"default": "./index.mjs"
|
|
39
|
+
},
|
|
40
|
+
"./internal": {
|
|
41
|
+
"types": "./internal.d.ts",
|
|
42
|
+
"default": "./internal.mjs"
|
|
43
|
+
},
|
|
44
|
+
"./package.json": "./package.json"
|
|
45
|
+
},
|
|
46
|
+
"sideEffects": false,
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@tanstack/query-core": "5.103.2"
|
|
49
|
+
},
|
|
50
|
+
"peerDependencies": {
|
|
51
|
+
"@angular/common": ">=20.1.0",
|
|
52
|
+
"@angular/core": ">=20.1.0"
|
|
53
|
+
}
|
|
54
|
+
}
|
package/providers.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { QueryClient } from '@tanstack/query-core';
|
|
2
|
+
import { EnvironmentProviders } from '@angular/core';
|
|
3
|
+
/**
|
|
4
|
+
* Provides a `QueryClient` and optional TanStack Query features.
|
|
5
|
+
* The factory runs once per injector in Angular's injection context, so it can
|
|
6
|
+
* call `inject()` and each SSR request can receive an independent cache.
|
|
7
|
+
*
|
|
8
|
+
* **Example - standalone**
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* import {
|
|
13
|
+
* provideTanStackQuery,
|
|
14
|
+
* QueryClient,
|
|
15
|
+
* } from '@tanstack/angular-query'
|
|
16
|
+
*
|
|
17
|
+
* bootstrapApplication(AppComponent, {
|
|
18
|
+
* providers: [provideTanStackQuery(() => new QueryClient())],
|
|
19
|
+
* })
|
|
20
|
+
* ```
|
|
21
|
+
*
|
|
22
|
+
* You can also enable optional developer tools by adding `withDevtools`. By
|
|
23
|
+
* default the tools will then be loaded when your app is in development mode.
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'
|
|
27
|
+
* import { withDevtools } from '@tanstack/angular-query-devtools'
|
|
28
|
+
*
|
|
29
|
+
* bootstrapApplication(AppComponent, {
|
|
30
|
+
* providers: [
|
|
31
|
+
* provideTanStackQuery(() => new QueryClient(), withDevtools()),
|
|
32
|
+
* ],
|
|
33
|
+
* })
|
|
34
|
+
* ```
|
|
35
|
+
*
|
|
36
|
+
* @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.
|
|
37
|
+
* @param features - Optional features to configure additional Query functionality.
|
|
38
|
+
* @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).
|
|
39
|
+
* @see https://tanstack.com/query/v5/docs/framework/angular/quick-start
|
|
40
|
+
* @see https://tanstack.com/query/v5/docs/framework/angular/devtools
|
|
41
|
+
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr
|
|
42
|
+
*/
|
|
43
|
+
export declare function provideTanStackQuery(queryClientFactory: () => QueryClient, ...features: ReadonlyArray<QueryFeature>): EnvironmentProviders;
|
|
44
|
+
declare const queryFeatureBrand: unique symbol;
|
|
45
|
+
/**
|
|
46
|
+
* Opaque configuration returned by Query feature functions such as `withHydrationKey`.
|
|
47
|
+
* Pass features to `provideTanStackQuery`; applications do not construct them directly.
|
|
48
|
+
*/
|
|
49
|
+
export interface QueryFeature {
|
|
50
|
+
/** @internal */
|
|
51
|
+
readonly [queryFeatureBrand]: true;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Creates a feature shared by Angular Query integration packages.
|
|
55
|
+
* @internal
|
|
56
|
+
* @param providers -
|
|
57
|
+
* @returns A Query feature.
|
|
58
|
+
*/
|
|
59
|
+
export declare function queryFeature(providers: EnvironmentProviders): QueryFeature;
|
|
60
|
+
/** @internal */
|
|
61
|
+
export declare function getQueryFeatureProviders(feature: QueryFeature): EnvironmentProviders;
|
|
62
|
+
/**
|
|
63
|
+
* Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /
|
|
64
|
+
* browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances
|
|
65
|
+
* so each has its own key. The default key applies when you do not add this feature.
|
|
66
|
+
*
|
|
67
|
+
* ```ts
|
|
68
|
+
* providers: [
|
|
69
|
+
* provideTanStackQuery(
|
|
70
|
+
* () => new QueryClient(),
|
|
71
|
+
* withHydrationKey('my-secondary-query-cache'),
|
|
72
|
+
* ),
|
|
73
|
+
* ]
|
|
74
|
+
* ```
|
|
75
|
+
*
|
|
76
|
+
* @param key - A unique string for this client's `TransferState` entry.
|
|
77
|
+
*/
|
|
78
|
+
export declare function withHydrationKey(key: string): QueryFeature;
|
|
79
|
+
/**
|
|
80
|
+
* Disables `TransferState` hydration and dehydration for the current environment injector.
|
|
81
|
+
*/
|
|
82
|
+
export declare function withNoQueryHydration(): QueryFeature;
|
|
83
|
+
export {};
|
package/providers.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { isPlatformServer, isPlatformBrowser } from "@angular/common";
|
|
2
|
+
import { makeEnvironmentProviders, provideEnvironmentInitializer, makeStateKey, InjectionToken, inject, DestroyRef, PLATFORM_ID, DOCUMENT, TransferState } from "@angular/core";
|
|
3
|
+
import { QueryClient, dehydrate, hydrate } from "@tanstack/query-core";
|
|
4
|
+
import { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from "./hydration-state-key.mjs";
|
|
5
|
+
import { injectQueryZone } from "./utils/inject-query-zone.mjs";
|
|
6
|
+
const INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE = new InjectionToken("", {
|
|
7
|
+
providedIn: "root",
|
|
8
|
+
factory: () => true
|
|
9
|
+
});
|
|
10
|
+
function configureQueryClient() {
|
|
11
|
+
const queryClient = inject(QueryClient);
|
|
12
|
+
const destroyRef = inject(DestroyRef);
|
|
13
|
+
const platformId = inject(PLATFORM_ID);
|
|
14
|
+
if (isPlatformServer(platformId)) {
|
|
15
|
+
const defaults = queryClient.getDefaultOptions();
|
|
16
|
+
queryClient.setDefaultOptions({
|
|
17
|
+
...defaults,
|
|
18
|
+
queries: { gcTime: Infinity, retry: false, ...defaults.queries },
|
|
19
|
+
mutations: { gcTime: Infinity, ...defaults.mutations }
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
const shouldHydrate = inject(INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE);
|
|
23
|
+
const hydrationStateKey = inject(
|
|
24
|
+
INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY
|
|
25
|
+
);
|
|
26
|
+
if (inject(DOCUMENT, { optional: true })) {
|
|
27
|
+
const transferState = inject(TransferState);
|
|
28
|
+
if (shouldHydrate && isPlatformServer(platformId)) {
|
|
29
|
+
transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient));
|
|
30
|
+
} else if (shouldHydrate && isPlatformBrowser(platformId)) {
|
|
31
|
+
const dehydratedState = transferState.get(hydrationStateKey, null);
|
|
32
|
+
if (dehydratedState) {
|
|
33
|
+
hydrate(queryClient, dehydratedState);
|
|
34
|
+
transferState.remove(hydrationStateKey);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
queryClient.mount();
|
|
39
|
+
destroyRef.onDestroy(() => queryClient.unmount());
|
|
40
|
+
}
|
|
41
|
+
function provideTanStackQuery(queryClientFactory, ...features) {
|
|
42
|
+
return makeEnvironmentProviders([
|
|
43
|
+
{
|
|
44
|
+
provide: QueryClient,
|
|
45
|
+
useFactory: () => injectQueryZone()(queryClientFactory)
|
|
46
|
+
},
|
|
47
|
+
...features.map(getQueryFeatureProviders),
|
|
48
|
+
provideEnvironmentInitializer(configureQueryClient)
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
const queryFeatureBrand = /* @__PURE__ */ Symbol("QueryFeature");
|
|
52
|
+
function queryFeature(providers) {
|
|
53
|
+
const feature = {
|
|
54
|
+
[queryFeatureBrand]: true,
|
|
55
|
+
ɵproviders: providers
|
|
56
|
+
};
|
|
57
|
+
return feature;
|
|
58
|
+
}
|
|
59
|
+
function getQueryFeatureProviders(feature) {
|
|
60
|
+
return feature.ɵproviders;
|
|
61
|
+
}
|
|
62
|
+
function withHydrationKey(key) {
|
|
63
|
+
return queryFeature(
|
|
64
|
+
makeEnvironmentProviders([
|
|
65
|
+
{
|
|
66
|
+
provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,
|
|
67
|
+
useValue: makeStateKey(key)
|
|
68
|
+
}
|
|
69
|
+
])
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
function withNoQueryHydration() {
|
|
73
|
+
return queryFeature(
|
|
74
|
+
makeEnvironmentProviders([
|
|
75
|
+
{
|
|
76
|
+
provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,
|
|
77
|
+
useValue: false
|
|
78
|
+
}
|
|
79
|
+
])
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
export {
|
|
83
|
+
getQueryFeatureProviders,
|
|
84
|
+
provideTanStackQuery,
|
|
85
|
+
queryFeature,
|
|
86
|
+
withHydrationKey,
|
|
87
|
+
withNoQueryHydration
|
|
88
|
+
};
|
|
89
|
+
//# sourceMappingURL=providers.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"providers.mjs","sources":["../src/providers.ts"],"sourcesContent":["import { isPlatformBrowser, isPlatformServer } from '@angular/common'\nimport {\n DOCUMENT,\n DestroyRef,\n InjectionToken,\n PLATFORM_ID,\n TransferState,\n inject,\n makeEnvironmentProviders,\n makeStateKey,\n provideEnvironmentInitializer,\n} from '@angular/core'\nimport { QueryClient, dehydrate, hydrate } from '@tanstack/query-core'\nimport { INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY } from './hydration-state-key'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport type { DehydratedState } from '@tanstack/query-core'\nimport type { EnvironmentProviders } from '@angular/core'\n\nconst INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE = new InjectionToken<boolean>('', {\n providedIn: 'root',\n factory: () => true,\n})\n\nfunction configureQueryClient() {\n const queryClient = inject(QueryClient)\n const destroyRef = inject(DestroyRef)\n const platformId = inject(PLATFORM_ID)\n\n if (isPlatformServer(platformId)) {\n // DOM emulation can fool core's runtime detection. Apply server defaults to\n // this client without changing other clients or global scheduling providers.\n const defaults = queryClient.getDefaultOptions()\n queryClient.setDefaultOptions({\n ...defaults,\n queries: { gcTime: Infinity, retry: false, ...defaults.queries },\n mutations: { gcTime: Infinity, ...defaults.mutations },\n })\n }\n const shouldHydrate = inject(INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE)\n const hydrationStateKey = inject(\n INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,\n )\n\n if (inject(DOCUMENT, { optional: true })) {\n const transferState = inject(TransferState)\n\n if (shouldHydrate && isPlatformServer(platformId)) {\n transferState.onSerialize(hydrationStateKey, () => dehydrate(queryClient))\n } else if (shouldHydrate && isPlatformBrowser(platformId)) {\n const dehydratedState = transferState.get(hydrationStateKey, null)\n if (dehydratedState) {\n hydrate(queryClient, dehydratedState)\n transferState.remove(hydrationStateKey)\n }\n }\n }\n\n queryClient.mount()\n destroyRef.onDestroy(() => queryClient.unmount())\n}\n\n/**\n * Provides a `QueryClient` and optional TanStack Query features.\n * The factory runs once per injector in Angular's injection context, so it can\n * call `inject()` and each SSR request can receive an independent cache.\n *\n * **Example - standalone**\n *\n * @example\n * ```ts\n * import {\n * provideTanStackQuery,\n * QueryClient,\n * } from '@tanstack/angular-query'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [provideTanStackQuery(() => new QueryClient())],\n * })\n * ```\n *\n * You can also enable optional developer tools by adding `withDevtools`. By\n * default the tools will then be loaded when your app is in development mode.\n *\n * ```ts\n * import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query'\n * import { withDevtools } from '@tanstack/angular-query-devtools'\n *\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideTanStackQuery(() => new QueryClient(), withDevtools()),\n * ],\n * })\n * ```\n *\n * @param queryClientFactory - Creates or resolves a `QueryClient` in the injection context.\n * @param features - Optional features to configure additional Query functionality.\n * @returns A single {@link EnvironmentProviders} value (do not spread into `providers`).\n * @see https://tanstack.com/query/v5/docs/framework/angular/quick-start\n * @see https://tanstack.com/query/v5/docs/framework/angular/devtools\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/ssr\n */\nexport function provideTanStackQuery(\n queryClientFactory: () => QueryClient,\n ...features: ReadonlyArray<QueryFeature>\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: QueryClient,\n useFactory: () => injectQueryZone()(queryClientFactory),\n },\n ...features.map(getQueryFeatureProviders),\n provideEnvironmentInitializer(configureQueryClient),\n ])\n}\n\nconst queryFeatureBrand: unique symbol = Symbol('QueryFeature')\n\n/**\n * Opaque configuration returned by Query feature functions such as `withHydrationKey`.\n * Pass features to `provideTanStackQuery`; applications do not construct them directly.\n */\nexport interface QueryFeature {\n /** @internal */\n readonly [queryFeatureBrand]: true\n}\n\ninterface InternalQueryFeature extends QueryFeature {\n readonly ɵproviders: EnvironmentProviders\n}\n\n/**\n * Creates a feature shared by Angular Query integration packages.\n * @internal\n * @param providers -\n * @returns A Query feature.\n */\nexport function queryFeature(providers: EnvironmentProviders): QueryFeature {\n const feature: InternalQueryFeature = {\n [queryFeatureBrand]: true,\n ɵproviders: providers,\n }\n\n return feature\n}\n\n/** @internal */\nexport function getQueryFeatureProviders(\n feature: QueryFeature,\n): EnvironmentProviders {\n return (feature as InternalQueryFeature).ɵproviders\n}\n\n/**\n * Sets a non-default serialization key for this injector's `QueryClient` cache (server dehydrate /\n * browser hydrate via `TransferState`). Use this when you have multiple `QueryClient` instances\n * so each has its own key. The default key applies when you do not add this feature.\n *\n * ```ts\n * providers: [\n * provideTanStackQuery(\n * () => new QueryClient(),\n * withHydrationKey('my-secondary-query-cache'),\n * ),\n * ]\n * ```\n *\n * @param key - A unique string for this client's `TransferState` entry.\n */\nexport function withHydrationKey(key: string): QueryFeature {\n return queryFeature(\n makeEnvironmentProviders([\n {\n provide: INTERNAL_TANSTACK_QUERY_HYDRATION_TRANSFER_KEY,\n useValue: makeStateKey<DehydratedState>(key),\n },\n ]),\n )\n}\n\n/**\n * Disables `TransferState` hydration and dehydration for the current environment injector.\n */\nexport function withNoQueryHydration(): QueryFeature {\n return queryFeature(\n makeEnvironmentProviders([\n {\n provide: INTERNAL_QUERY_CLIENT_SHOULD_HYDRATE,\n useValue: false,\n },\n ]),\n )\n}\n"],"names":[],"mappings":";;;;;AAkBA,MAAM,uCAAuC,IAAI,eAAwB,IAAI;AAAA,EAC3E,YAAY;AAAA,EACZ,SAAS,MAAM;AACjB,CAAC;AAED,SAAS,uBAAuB;AAC9B,QAAM,cAAc,OAAO,WAAW;AACtC,QAAM,aAAa,OAAO,UAAU;AACpC,QAAM,aAAa,OAAO,WAAW;AAErC,MAAI,iBAAiB,UAAU,GAAG;AAGhC,UAAM,WAAW,YAAY,kBAAA;AAC7B,gBAAY,kBAAkB;AAAA,MAC5B,GAAG;AAAA,MACH,SAAS,EAAE,QAAQ,UAAU,OAAO,OAAO,GAAG,SAAS,QAAA;AAAA,MACvD,WAAW,EAAE,QAAQ,UAAU,GAAG,SAAS,UAAA;AAAA,IAAU,CACtD;AAAA,EACH;AACA,QAAM,gBAAgB,OAAO,oCAAoC;AACjE,QAAM,oBAAoB;AAAA,IACxB;AAAA,EAAA;AAGF,MAAI,OAAO,UAAU,EAAE,UAAU,KAAA,CAAM,GAAG;AACxC,UAAM,gBAAgB,OAAO,aAAa;AAE1C,QAAI,iBAAiB,iBAAiB,UAAU,GAAG;AACjD,oBAAc,YAAY,mBAAmB,MAAM,UAAU,WAAW,CAAC;AAAA,IAC3E,WAAW,iBAAiB,kBAAkB,UAAU,GAAG;AACzD,YAAM,kBAAkB,cAAc,IAAI,mBAAmB,IAAI;AACjE,UAAI,iBAAiB;AACnB,gBAAQ,aAAa,eAAe;AACpC,sBAAc,OAAO,iBAAiB;AAAA,MACxC;AAAA,IACF;AAAA,EACF;AAEA,cAAY,MAAA;AACZ,aAAW,UAAU,MAAM,YAAY,QAAA,CAAS;AAClD;AA0CO,SAAS,qBACd,uBACG,UACmB;AACtB,SAAO,yBAAyB;AAAA,IAC9B;AAAA,MACE,SAAS;AAAA,MACT,YAAY,MAAM,gBAAA,EAAkB,kBAAkB;AAAA,IAAA;AAAA,IAExD,GAAG,SAAS,IAAI,wBAAwB;AAAA,IACxC,8BAA8B,oBAAoB;AAAA,EAAA,CACnD;AACH;AAEA,MAAM,2CAA0C,cAAc;AAqBvD,SAAS,aAAa,WAA+C;AAC1E,QAAM,UAAgC;AAAA,IACpC,CAAC,iBAAiB,GAAG;AAAA,IACrB,YAAY;AAAA,EAAA;AAGd,SAAO;AACT;AAGO,SAAS,yBACd,SACsB;AACtB,SAAQ,QAAiC;AAC3C;AAkBO,SAAS,iBAAiB,KAA2B;AAC1D,SAAO;AAAA,IACL,yBAAyB;AAAA,MACvB;AAAA,QACE,SAAS;AAAA,QACT,UAAU,aAA8B,GAAG;AAAA,MAAA;AAAA,IAC7C,CACD;AAAA,EAAA;AAEL;AAKO,SAAS,uBAAqC;AACnD,SAAO;AAAA,IACL,yBAAyB;AAAA,MACvB;AAAA,QACE,SAAS;AAAA,QACT,UAAU;AAAA,MAAA;AAAA,IACZ,CACD;AAAA,EAAA;AAEL;"}
|