@trpc/tanstack-react-query 11.27.0 → 11.28.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/dist/createOptionsProxy-CSjaFTcE.d.cts.map +1 -1
- package/dist/createOptionsProxy-DrOxGLOk.d.mts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.react-server.cjs +1 -1
- package/dist/index.react-server.mjs +1 -1
- package/dist/{src-BTWtlvMP.cjs → src-8dapKwo_.cjs} +8 -9
- package/dist/{src-DJH1vKsX.mjs → src-DBCpxixG.mjs} +9 -10
- package/dist/src-DBCpxixG.mjs.map +1 -0
- package/dist/unstable-handles/index.cjs +1 -1
- package/dist/unstable-handles/index.mjs +1 -1
- package/dist/{utils-DBAP6Vqs.cjs → utils-B3wZ5_eo.cjs} +98 -86
- package/dist/{utils-Ds4S0kXF.mjs → utils-DTVvWT-Z.mjs} +99 -81
- package/dist/utils-DTVvWT-Z.mjs.map +1 -0
- package/package.json +6 -6
- package/skills/react-query-classic-migration/SKILL.md +1 -1
- package/skills/react-query-setup/SKILL.md +1 -1
- package/skills/react-query-setup/references/client-tanstack-react-query-usage.md +20 -0
- package/src/internals/queryOptions.ts +10 -8
- package/src/internals/utils.ts +30 -123
- package/dist/src-DJH1vKsX.mjs.map +0 -1
- package/dist/utils-Ds4S0kXF.mjs.map +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { skipToken } from "@tanstack/react-query";
|
|
1
|
+
import { experimental_streamedQuery, skipToken } from "@tanstack/react-query";
|
|
2
2
|
import { isFunction, isObject, run } from "@trpc/server/unstable-core-do-not-import";
|
|
3
3
|
// \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
|
|
4
4
|
function _typeof(o) {
|
|
@@ -98,6 +98,85 @@ function AsyncFromSyncIterator(r) {
|
|
|
98
98
|
}
|
|
99
99
|
}, new AsyncFromSyncIterator(r);
|
|
100
100
|
}
|
|
101
|
+
// \0@oxc-project+runtime@0.157.0/helpers/esm/OverloadYield.js
|
|
102
|
+
function _OverloadYield(e, d) {
|
|
103
|
+
this.v = e, this.k = d;
|
|
104
|
+
}
|
|
105
|
+
// \0@oxc-project+runtime@0.157.0/helpers/esm/asyncGeneratorDelegate.js
|
|
106
|
+
function _asyncGeneratorDelegate(t) {
|
|
107
|
+
var e = {}, n = !1;
|
|
108
|
+
function pump(e, r) {
|
|
109
|
+
return n = !0, r = new Promise(function(n) {
|
|
110
|
+
n(t[e](r));
|
|
111
|
+
}), {
|
|
112
|
+
done: !1,
|
|
113
|
+
value: new _OverloadYield(r, 1)
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return e["undefined" != typeof Symbol && Symbol.iterator || "@@iterator"] = function() {
|
|
117
|
+
return this;
|
|
118
|
+
}, e.next = function(t) {
|
|
119
|
+
return n ? (n = !1, t) : pump("next", t);
|
|
120
|
+
}, "function" == typeof t["throw"] && (e["throw"] = function(t) {
|
|
121
|
+
if (n) throw n = !1, t;
|
|
122
|
+
return pump("throw", t);
|
|
123
|
+
}), "function" == typeof t["return"] && (e["return"] = function(t) {
|
|
124
|
+
return n ? (n = !1, t) : pump("return", t);
|
|
125
|
+
}), e;
|
|
126
|
+
}
|
|
127
|
+
// \0@oxc-project+runtime@0.157.0/helpers/esm/wrapAsyncGenerator.js
|
|
128
|
+
function _wrapAsyncGenerator(e) {
|
|
129
|
+
return function() {
|
|
130
|
+
return new AsyncGenerator(e.apply(this, arguments));
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function AsyncGenerator(e) {
|
|
134
|
+
var t, n;
|
|
135
|
+
function resume(t, n) {
|
|
136
|
+
try {
|
|
137
|
+
var r = e[t](n), o = r.value, u = o instanceof _OverloadYield;
|
|
138
|
+
Promise.resolve(u ? o.v : o).then(function(n) {
|
|
139
|
+
if (u) {
|
|
140
|
+
var i = "return" === t && o.k ? t : "next";
|
|
141
|
+
if (!o.k || n.done) return resume(i, n);
|
|
142
|
+
n = e[i](n).value;
|
|
143
|
+
}
|
|
144
|
+
settle(!!r.done, n);
|
|
145
|
+
}, function(e) {
|
|
146
|
+
resume("throw", e);
|
|
147
|
+
});
|
|
148
|
+
} catch (e) {
|
|
149
|
+
settle(2, e);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
function settle(e, r) {
|
|
153
|
+
2 === e ? t.reject(r) : t.resolve({
|
|
154
|
+
value: r,
|
|
155
|
+
done: e
|
|
156
|
+
}), (t = t.next) ? resume(t.key, t.arg) : n = null;
|
|
157
|
+
}
|
|
158
|
+
this._invoke = function(e, r) {
|
|
159
|
+
return new Promise(function(o, u) {
|
|
160
|
+
var i = {
|
|
161
|
+
key: e,
|
|
162
|
+
arg: r,
|
|
163
|
+
resolve: o,
|
|
164
|
+
reject: u,
|
|
165
|
+
next: null
|
|
166
|
+
};
|
|
167
|
+
n ? n = n.next = i : (t = n = i, resume(e, r));
|
|
168
|
+
});
|
|
169
|
+
}, "function" != typeof e["return"] && (this["return"] = void 0);
|
|
170
|
+
}
|
|
171
|
+
AsyncGenerator.prototype["function" == typeof Symbol && Symbol.asyncIterator || "@@asyncIterator"] = function() {
|
|
172
|
+
return this;
|
|
173
|
+
}, AsyncGenerator.prototype.next = function(e) {
|
|
174
|
+
return this._invoke("next", e);
|
|
175
|
+
}, AsyncGenerator.prototype["throw"] = function(e) {
|
|
176
|
+
return this._invoke("throw", e);
|
|
177
|
+
}, AsyncGenerator.prototype["return"] = function(e) {
|
|
178
|
+
return this._invoke("return", e);
|
|
179
|
+
};
|
|
101
180
|
// \0@oxc-project+runtime@0.157.0/helpers/esm/objectWithoutPropertiesLoose.js
|
|
102
181
|
function _objectWithoutPropertiesLoose(r, e) {
|
|
103
182
|
if (null == r) return {};
|
|
@@ -161,91 +240,30 @@ function getClientArgs(queryKey, opts, infiniteParams) {
|
|
|
161
240
|
];
|
|
162
241
|
}
|
|
163
242
|
/**
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*/
|
|
168
|
-
function getQueryAtKeyHash(opts) {
|
|
169
|
-
try {
|
|
170
|
-
const { queryHash } = opts.client.defaultQueryOptions({ queryKey: opts.queryKey });
|
|
171
|
-
return opts.client.getQueryCache().get(queryHash);
|
|
172
|
-
} catch (_unused) {
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Finds the query running this fetch, so that its stream only writes while
|
|
178
|
-
* TanStack Query still waits for that fetch. Call it before the request starts,
|
|
179
|
-
* as an older request can answer last. Takes what it needs from the query
|
|
180
|
-
* function's context, as reading its `signal` would change what unmounting does.
|
|
243
|
+
* Streams a procedure's async iterable into the query with TanStack Query's
|
|
244
|
+
* `streamedQuery`, which stops writing to the cache once the fetch is
|
|
245
|
+
* cancelled or replaced by a refetch.
|
|
181
246
|
* @internal
|
|
182
247
|
*/
|
|
183
|
-
function
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
return { write(state) {
|
|
190
|
-
var _built;
|
|
191
|
-
(_built = built) !== null && _built !== void 0 || (built = build());
|
|
192
|
-
built.setState(state);
|
|
193
|
-
} };
|
|
248
|
+
async function streamIntoQuery(opts) {
|
|
249
|
+
const context = opts.context.client ? opts.context : _objectSpread2(_objectSpread2({}, opts.context), {}, { client: opts.queryClient });
|
|
250
|
+
let finished = false;
|
|
251
|
+
const { iterable } = opts;
|
|
252
|
+
function readToEnd() {
|
|
253
|
+
return _readToEnd.apply(this, arguments);
|
|
194
254
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
});
|
|
202
|
-
let checkShared = true;
|
|
203
|
-
if (!query || !isOwn(query) || !isFetching(query)) {
|
|
204
|
-
const queries = cache.findAll({ predicate: (it) => isOwn(it) && isFetching(it) });
|
|
205
|
-
query = queries.length === 1 ? queries[0] : void 0;
|
|
206
|
-
checkShared = false;
|
|
255
|
+
function _readToEnd() {
|
|
256
|
+
_readToEnd = _wrapAsyncGenerator(function* () {
|
|
257
|
+
yield* _asyncGeneratorDelegate(_asyncIterator(iterable));
|
|
258
|
+
finished = true;
|
|
259
|
+
});
|
|
260
|
+
return _readToEnd.apply(this, arguments);
|
|
207
261
|
}
|
|
208
|
-
const fetchPromise = query === null || query === void 0 ? void 0 : query.promise;
|
|
209
|
-
return { write(state) {
|
|
210
|
-
if (checkShared) {
|
|
211
|
-
checkShared = false;
|
|
212
|
-
if (cache.findAll({ predicate: (it) => isOwn(it) && it !== query }).length > 0) query = void 0;
|
|
213
|
-
}
|
|
214
|
-
if (query && query.promise === fetchPromise && isFetching(query)) query.setState(state);
|
|
215
|
-
} };
|
|
216
|
-
}
|
|
217
|
-
/**
|
|
218
|
-
* Always reads to the end: leaving the loop would abort an older stream on the
|
|
219
|
-
* server, which only `abortOnUnmount` asks for, and the return value is the
|
|
220
|
-
* fetch's result.
|
|
221
|
-
* @internal
|
|
222
|
-
*/
|
|
223
|
-
async function buildQueryFromAsyncIterable(asyncIterable, queryFetch) {
|
|
224
|
-
queryFetch.write({
|
|
225
|
-
data: [],
|
|
226
|
-
status: "success"
|
|
227
|
-
});
|
|
228
|
-
const aggregate = [];
|
|
229
|
-
var _iteratorAbruptCompletion = false;
|
|
230
|
-
var _didIteratorError = false;
|
|
231
|
-
var _iteratorError;
|
|
232
262
|
try {
|
|
233
|
-
|
|
234
|
-
const value = _step.value;
|
|
235
|
-
aggregate.push(value);
|
|
236
|
-
queryFetch.write({ data: [...aggregate] });
|
|
237
|
-
}
|
|
238
|
-
} catch (err) {
|
|
239
|
-
_didIteratorError = true;
|
|
240
|
-
_iteratorError = err;
|
|
263
|
+
return await experimental_streamedQuery({ streamFn: readToEnd })(context);
|
|
241
264
|
} finally {
|
|
242
|
-
|
|
243
|
-
if (_iteratorAbruptCompletion && _iterator.return != null) await _iterator.return();
|
|
244
|
-
} finally {
|
|
245
|
-
if (_didIteratorError) throw _iteratorError;
|
|
246
|
-
}
|
|
265
|
+
if (!finished) opts.abortController.abort();
|
|
247
266
|
}
|
|
248
|
-
return aggregate;
|
|
249
267
|
}
|
|
250
268
|
/**
|
|
251
269
|
* To allow easy interactions with groups of related queries, such as
|
|
@@ -285,6 +303,6 @@ function getMutationKeyInternal(opts) {
|
|
|
285
303
|
function unwrapLazyArg(valueOrLazy) {
|
|
286
304
|
return isFunction(valueOrLazy) ? valueOrLazy() : valueOrLazy;
|
|
287
305
|
}
|
|
288
|
-
export {
|
|
306
|
+
export { readQueryKey as a, _objectSpread2 as c, getQueryKeyInternal as i, _defineProperty as l, getClientArgs as n, streamIntoQuery as o, getMutationKeyInternal as r, unwrapLazyArg as s, createTRPCOptionsResult as t };
|
|
289
307
|
|
|
290
|
-
//# sourceMappingURL=utils-
|
|
308
|
+
//# sourceMappingURL=utils-DTVvWT-Z.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils-DTVvWT-Z.mjs","names":["streamedQuery"],"sources":["../src/internals/utils.ts"],"sourcesContent":["import {\n skipToken,\n experimental_streamedQuery as streamedQuery,\n type QueryClient,\n type QueryFunctionContext,\n type QueryKey,\n} from '@tanstack/react-query';\nimport {\n isFunction,\n isObject,\n run,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type {\n AnyTRPCMutationKey,\n AnyTRPCQueryKey,\n FeatureFlags,\n QueryType,\n TRPCMutationKeyWithoutPrefix,\n TRPCQueryKey,\n TRPCQueryKeyWithoutPrefix,\n TRPCQueryKeyWithPrefix,\n TRPCQueryOptionsResult,\n} from './types';\n\n/**\n * @internal\n */\nexport function createTRPCOptionsResult(value: {\n path: string[];\n}): TRPCQueryOptionsResult['trpc'] {\n const path = value.path.join('.');\n\n return {\n path,\n };\n}\n\nexport function isPrefixedQueryKey(\n queryKey: TRPCQueryKey<any>,\n): queryKey is TRPCQueryKeyWithPrefix {\n return queryKey.length >= 3;\n}\n\nexport function readQueryKey(queryKey: AnyTRPCQueryKey) {\n if (isPrefixedQueryKey(queryKey)) {\n return {\n type: 'prefixed' as const,\n prefix: queryKey[0],\n path: queryKey[1],\n args: queryKey[2],\n };\n } else {\n return {\n type: 'unprefixed' as const,\n prefix: undefined,\n path: queryKey[0],\n args: queryKey[1],\n };\n }\n}\n\n/**\n * @internal\n */\nexport function getClientArgs<TOptions, TFeatureFlags extends FeatureFlags>(\n queryKey: TRPCQueryKey<TFeatureFlags['keyPrefix']>,\n opts: TOptions,\n infiniteParams?: {\n pageParam: any;\n direction: 'forward' | 'backward';\n },\n) {\n const queryKeyData = readQueryKey(queryKey);\n\n let input = queryKeyData.args?.input;\n if (infiniteParams) {\n input = {\n ...(queryKeyData.args?.input ?? {}),\n ...(infiniteParams.pageParam !== undefined\n ? { cursor: infiniteParams.pageParam }\n : {}),\n direction: infiniteParams.direction,\n };\n }\n return [queryKeyData.path.join('.'), input, (opts as any)?.trpc] as const;\n}\n\n/**\n * Streams a procedure's async iterable into the query with TanStack Query's\n * `streamedQuery`, which stops writing to the cache once the fetch is\n * cancelled or replaced by a refetch.\n * @internal\n */\nexport async function streamIntoQuery(opts: {\n iterable: AsyncIterable<unknown>;\n context: QueryFunctionContext<QueryKey>;\n queryClient: QueryClient;\n /** Aborts the request, for a stream that isn't read to the end. */\n abortController: AbortController;\n}) {\n // a context built by hand can lack `client`; a real one is passed as is, as\n // spreading it would read `signal` and make unmounting cancel the query\n const context = opts.context.client\n ? opts.context\n : { ...opts.context, client: opts.queryClient };\n let finished = false;\n const { iterable } = opts;\n async function* readToEnd() {\n yield* iterable;\n finished = true;\n }\n try {\n return await streamedQuery<unknown>({ streamFn: readToEnd })(context);\n } finally {\n // `streamedQuery` stops reading, or never starts, once the fetch is\n // cancelled: abort the request so the server stops streaming too\n if (!finished) {\n opts.abortController.abort();\n }\n }\n}\n\n/**\n * To allow easy interactions with groups of related queries, such as\n * invalidating all queries of a router, we use an array as the path when\n * storing in tanstack query.\n *\n * @internal\n */\nexport function getQueryKeyInternal(opts: {\n path: string[];\n input?: unknown;\n type: QueryType;\n prefix: string | undefined;\n}): AnyTRPCQueryKey {\n const key = run((): TRPCQueryKeyWithoutPrefix => {\n const { input, type } = opts;\n\n // Construct a query key that is easy to destructure and flexible for\n // partial selecting etc.\n // https://github.com/trpc/trpc/issues/3128\n\n // some parts of the path may be dot-separated, split them up\n const splitPath = opts.path.flatMap((part) => part.split('.'));\n\n if (typeof input === 'undefined' && type === 'any') {\n // this matches also all mutations (see `getMutationKeyInternal`)\n\n // for `utils.invalidate()` to match all queries (including vanilla react-query)\n // we don't want nested array if path is empty, i.e. `[]` instead of `[[]]`\n return splitPath.length ? [splitPath] : ([] as unknown as TRPCQueryKey);\n }\n\n if (\n type === 'infinite' &&\n isObject(input) &&\n ('direction' in input || 'cursor' in input)\n ) {\n const {\n cursor: _,\n direction: __,\n ...inputWithoutCursorAndDirection\n } = input;\n return [\n splitPath,\n {\n input: inputWithoutCursorAndDirection,\n type: 'infinite',\n },\n ];\n }\n\n return [\n splitPath,\n {\n ...(typeof input !== 'undefined' &&\n input !== skipToken && { input: input }),\n ...(type && type !== 'any' && { type: type }),\n },\n ];\n });\n\n if (opts.prefix) {\n key.unshift([opts.prefix]);\n }\n return key;\n}\n\n/**\n * @internal\n */\nexport function getMutationKeyInternal(opts: {\n prefix: string | undefined;\n path: string[];\n}): AnyTRPCMutationKey {\n // some parts of the path may be dot-separated, split them up\n const key: TRPCMutationKeyWithoutPrefix = [\n opts.path.flatMap((part) => part.split('.')),\n ];\n\n if (opts.prefix) {\n key.unshift([opts.prefix]);\n }\n return key;\n}\n\n/**\n * @internal\n */\nexport function unwrapLazyArg<T>(valueOrLazy: T | (() => T)): T {\n return (isFunction(valueOrLazy) ? valueOrLazy() : valueOrLazy) as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAiB,aAA+B;CAC9D,OAAQ,WAAW,WAAW,IAAI,YAAY,IAAI;AACpD"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trpc/tanstack-react-query",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "11.
|
|
4
|
+
"version": "11.28.0",
|
|
5
5
|
"description": "TanStack React Query Integration for tRPC",
|
|
6
6
|
"author": "juliusmarminge",
|
|
7
7
|
"license": "MIT",
|
|
@@ -58,17 +58,17 @@
|
|
|
58
58
|
"skills"
|
|
59
59
|
],
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"@tanstack/react-query": "^5.
|
|
62
|
-
"@trpc/client": "11.
|
|
63
|
-
"@trpc/server": "11.
|
|
61
|
+
"@tanstack/react-query": "^5.106.0",
|
|
62
|
+
"@trpc/client": "11.28.0",
|
|
63
|
+
"@trpc/server": "11.28.0",
|
|
64
64
|
"react": ">=18.2.0",
|
|
65
65
|
"typescript": ">=5.7.2"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
68
|
"@tanstack/intent": "0.5.6",
|
|
69
69
|
"@tanstack/react-query": "^5.107.1",
|
|
70
|
-
"@trpc/client": "11.
|
|
71
|
-
"@trpc/server": "11.
|
|
70
|
+
"@trpc/client": "11.28.0",
|
|
71
|
+
"@trpc/server": "11.28.0",
|
|
72
72
|
"@types/node": "^24.19.2",
|
|
73
73
|
"@types/react": "^19.3.0",
|
|
74
74
|
"event-source-polyfill": "^1.0.31",
|
|
@@ -113,6 +113,26 @@ const query = useQuery(
|
|
|
113
113
|
|
|
114
114
|
The result can be passed to `useQuery` or `useSuspenseQuery` hooks or query client methods like `fetchQuery`, `prefetchQuery`, `prefetchInfiniteQuery`, `invalidateQueries`, etc.
|
|
115
115
|
|
|
116
|
+
#### Streaming responses
|
|
117
|
+
|
|
118
|
+
A query that returns an async generator streams with [`httpBatchStreamLink`](https://trpc.io/docs/client/links/httpBatchStreamLink#generators). `data` is an array of the chunks so far, through TanStack Query's [`experimental_streamedQuery`](https://tanstack.com/query/latest/docs/framework/react/reference/functions/experimental_streamedQuery):
|
|
119
|
+
|
|
120
|
+
- The query is `pending` until the first chunk, then `success`, and `fetching` until the last chunk.
|
|
121
|
+
- When a refetch's response arrives, `data` is cleared and the query is `pending` until its first chunk.
|
|
122
|
+
- A refetch or `queryClient.cancelQueries()` stops the older stream: its chunks no longer reach the cache, and its request is aborted at its next chunk.
|
|
123
|
+
- Unmounting doesn't stop the stream, unless you set `trpc: { abortOnUnmount: true }`.
|
|
124
|
+
|
|
125
|
+
```tsx no-check
|
|
126
|
+
import { useQuery } from '@tanstack/react-query';
|
|
127
|
+
import { useTRPC } from './trpc';
|
|
128
|
+
|
|
129
|
+
export function Numbers() {
|
|
130
|
+
const trpc = useTRPC();
|
|
131
|
+
const query = useQuery(trpc.numbers.queryOptions());
|
|
132
|
+
return <pre>{query.data?.join(', ')}</pre>;
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
116
136
|
### `infiniteQueryOptions` - querying infinite data
|
|
117
137
|
|
|
118
138
|
Available for all query procedures that take a cursor input. Provides a type-safe wrapper around [Tanstack's `infiniteQueryOptions` function](https://tanstack.com/query/latest/docs/framework/react/reference/infiniteQueryOptions). The first argument is the input for the procedure, and the second argument accepts any native Tanstack React Query options.
|
|
@@ -23,10 +23,9 @@ import type {
|
|
|
23
23
|
TRPCQueryOptionsResult,
|
|
24
24
|
} from './types';
|
|
25
25
|
import {
|
|
26
|
-
buildQueryFromAsyncIterable,
|
|
27
26
|
createTRPCOptionsResult,
|
|
28
27
|
getClientArgs,
|
|
29
|
-
|
|
28
|
+
streamIntoQuery,
|
|
30
29
|
unwrapLazyArg,
|
|
31
30
|
} from './utils';
|
|
32
31
|
|
|
@@ -251,25 +250,28 @@ export function trpcQueryOptions<TFeatureFlags extends FeatureFlags>(args: {
|
|
|
251
250
|
unknown,
|
|
252
251
|
TRPCQueryKey<TFeatureFlags['keyPrefix']>
|
|
253
252
|
> = async (queryFnContext) => {
|
|
253
|
+
// aborted if the request answers with a stream that isn't read to the end
|
|
254
|
+
const abortController = new AbortController();
|
|
254
255
|
const actualOpts = {
|
|
255
256
|
...opts,
|
|
256
257
|
trpc: {
|
|
257
258
|
...opts?.trpc,
|
|
258
259
|
...(opts?.trpc?.abortOnUnmount
|
|
259
260
|
? { signal: queryFnContext.signal }
|
|
260
|
-
: { signal:
|
|
261
|
+
: { signal: abortController.signal }),
|
|
261
262
|
},
|
|
262
263
|
};
|
|
263
264
|
const queryKey = queryFnContext.queryKey;
|
|
264
|
-
const queryFetch = trackQueryFetch({
|
|
265
|
-
context: queryFnContext,
|
|
266
|
-
fallback: { client: queryClient, queryKey },
|
|
267
|
-
});
|
|
268
265
|
|
|
269
266
|
const result = await query(...getClientArgs(queryKey, actualOpts));
|
|
270
267
|
|
|
271
268
|
if (isAsyncIterable(result)) {
|
|
272
|
-
return
|
|
269
|
+
return streamIntoQuery({
|
|
270
|
+
iterable: result,
|
|
271
|
+
context: queryFnContext,
|
|
272
|
+
queryClient,
|
|
273
|
+
abortController,
|
|
274
|
+
});
|
|
273
275
|
}
|
|
274
276
|
|
|
275
277
|
return result;
|
package/src/internals/utils.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
skipToken,
|
|
3
|
-
|
|
3
|
+
experimental_streamedQuery as streamedQuery,
|
|
4
4
|
type QueryClient,
|
|
5
|
-
type
|
|
5
|
+
type QueryFunctionContext,
|
|
6
|
+
type QueryKey,
|
|
6
7
|
} from '@tanstack/react-query';
|
|
7
8
|
import {
|
|
8
9
|
isFunction,
|
|
@@ -85,132 +86,38 @@ export function getClientArgs<TOptions, TFeatureFlags extends FeatureFlags>(
|
|
|
85
86
|
}
|
|
86
87
|
|
|
87
88
|
/**
|
|
88
|
-
*
|
|
89
|
-
*
|
|
90
|
-
*
|
|
91
|
-
*/
|
|
92
|
-
function getQueryAtKeyHash(opts: {
|
|
93
|
-
client: QueryClient;
|
|
94
|
-
queryKey: AnyTRPCQueryKey;
|
|
95
|
-
}) {
|
|
96
|
-
try {
|
|
97
|
-
const { queryHash } = opts.client.defaultQueryOptions({
|
|
98
|
-
queryKey: opts.queryKey,
|
|
99
|
-
});
|
|
100
|
-
return opts.client.getQueryCache().get(queryHash);
|
|
101
|
-
} catch {
|
|
102
|
-
// only the query's own `queryKeyHashFn` can hash this key
|
|
103
|
-
return undefined;
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Finds the query running this fetch, so that its stream only writes while
|
|
109
|
-
* TanStack Query still waits for that fetch. Call it before the request starts,
|
|
110
|
-
* as an older request can answer last. Takes what it needs from the query
|
|
111
|
-
* function's context, as reading its `signal` would change what unmounting does.
|
|
89
|
+
* Streams a procedure's async iterable into the query with TanStack Query's
|
|
90
|
+
* `streamedQuery`, which stops writing to the cache once the fetch is
|
|
91
|
+
* cancelled or replaced by a refetch.
|
|
112
92
|
* @internal
|
|
113
93
|
*/
|
|
114
|
-
export function
|
|
115
|
-
|
|
116
|
-
context:
|
|
117
|
-
|
|
118
|
-
|
|
94
|
+
export async function streamIntoQuery(opts: {
|
|
95
|
+
iterable: AsyncIterable<unknown>;
|
|
96
|
+
context: QueryFunctionContext<QueryKey>;
|
|
97
|
+
queryClient: QueryClient;
|
|
98
|
+
/** Aborts the request, for a stream that isn't read to the end. */
|
|
99
|
+
abortController: AbortController;
|
|
119
100
|
}) {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
write(state: Partial<QueryState>) {
|
|
131
|
-
built ??= build();
|
|
132
|
-
built.setState(state);
|
|
133
|
-
},
|
|
134
|
-
};
|
|
101
|
+
// a context built by hand can lack `client`; a real one is passed as is, as
|
|
102
|
+
// spreading it would read `signal` and make unmounting cancel the query
|
|
103
|
+
const context = opts.context.client
|
|
104
|
+
? opts.context
|
|
105
|
+
: { ...opts.context, client: opts.queryClient };
|
|
106
|
+
let finished = false;
|
|
107
|
+
const { iterable } = opts;
|
|
108
|
+
async function* readToEnd() {
|
|
109
|
+
yield* iterable;
|
|
110
|
+
finished = true;
|
|
135
111
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
// The query is usually at the hash its client gives the key: a cheap lookup.
|
|
145
|
-
// One with its own `queryHash` or `queryKeyHashFn` is elsewhere, so a miss
|
|
146
|
-
// looks through the cache. A hit can be the wrong query when a spread gave
|
|
147
|
-
// this key array to one with its own `queryHash`, so a stream checks once,
|
|
148
|
-
// at its first write, that no other query has the array. That check can't
|
|
149
|
-
// see such a query once it has left the cache: if this is its fetch and it
|
|
150
|
-
// was removed before the stream started, the chunks reach the query at this
|
|
151
|
-
// hash while that query's fetch runs. The final result is unaffected.
|
|
152
|
-
let query = getQueryAtKeyHash({ client, queryKey: opts.context.queryKey });
|
|
153
|
-
let checkShared = true;
|
|
154
|
-
if (!query || !isOwn(query) || !isFetching(query)) {
|
|
155
|
-
// A fetch that can't tell which query is its own writes to none.
|
|
156
|
-
const queries = cache.findAll({
|
|
157
|
-
predicate: (it) => isOwn(it) && isFetching(it),
|
|
158
|
-
});
|
|
159
|
-
query = queries.length === 1 ? queries[0] : undefined;
|
|
160
|
-
checkShared = false;
|
|
161
|
-
}
|
|
162
|
-
// Each fetch has its own promise, which a refetch replaces, and cancelling or
|
|
163
|
-
// resetting the query stops the writes too. A silent cancel without `revert`,
|
|
164
|
-
// `cancelQueries(filters, { silent: true, revert: false })`, differs. On
|
|
165
|
-
// TanStack Query 5.80 the query keeps the promise, so the stream goes on
|
|
166
|
-
// writing, as before this change. On 5.105 and later the promise is dropped:
|
|
167
|
-
// the writes stop and the query stays fetching with the data it had, the
|
|
168
|
-
// state TanStack leaves after a silent cancel, where before they went on.
|
|
169
|
-
const fetchPromise = query?.promise;
|
|
170
|
-
|
|
171
|
-
return {
|
|
172
|
-
write(state: Partial<QueryState>) {
|
|
173
|
-
if (checkShared) {
|
|
174
|
-
// only streams write, so only they pay for looking through the cache
|
|
175
|
-
checkShared = false;
|
|
176
|
-
const shared = cache.findAll({
|
|
177
|
-
predicate: (it) => isOwn(it) && it !== query,
|
|
178
|
-
});
|
|
179
|
-
if (shared.length > 0) {
|
|
180
|
-
query = undefined;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
if (query && query.promise === fetchPromise && isFetching(query)) {
|
|
184
|
-
query.setState(state);
|
|
185
|
-
}
|
|
186
|
-
},
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
|
|
190
|
-
/**
|
|
191
|
-
* Always reads to the end: leaving the loop would abort an older stream on the
|
|
192
|
-
* server, which only `abortOnUnmount` asks for, and the return value is the
|
|
193
|
-
* fetch's result.
|
|
194
|
-
* @internal
|
|
195
|
-
*/
|
|
196
|
-
export async function buildQueryFromAsyncIterable(
|
|
197
|
-
asyncIterable: AsyncIterable<unknown>,
|
|
198
|
-
queryFetch: ReturnType<typeof trackQueryFetch>,
|
|
199
|
-
) {
|
|
200
|
-
queryFetch.write({
|
|
201
|
-
data: [],
|
|
202
|
-
status: 'success',
|
|
203
|
-
});
|
|
204
|
-
|
|
205
|
-
const aggregate: unknown[] = [];
|
|
206
|
-
for await (const value of asyncIterable) {
|
|
207
|
-
aggregate.push(value);
|
|
208
|
-
|
|
209
|
-
queryFetch.write({
|
|
210
|
-
data: [...aggregate],
|
|
211
|
-
});
|
|
112
|
+
try {
|
|
113
|
+
return await streamedQuery<unknown>({ streamFn: readToEnd })(context);
|
|
114
|
+
} finally {
|
|
115
|
+
// `streamedQuery` stops reading, or never starts, once the fetch is
|
|
116
|
+
// cancelled: abort the request so the server stops streaming too
|
|
117
|
+
if (!finished) {
|
|
118
|
+
opts.abortController.abort();
|
|
119
|
+
}
|
|
212
120
|
}
|
|
213
|
-
return aggregate;
|
|
214
121
|
}
|
|
215
122
|
|
|
216
123
|
/**
|