Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

streamedQuery.ts

75 lines2.7 KB

1import { addToEnd } from './utils'
2import type { QueryFunction, QueryFunctionContext, QueryKey } from './types'
3​
4/**
5 * This is a helper function to create a query function that streams data from an AsyncIterable.
6 * Data will be an Array of all the chunks received.
7 * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
8 * The query will stay in fetchStatus 'fetching' until the stream ends.
9 * @param queryFn - The function that returns an AsyncIterable to stream data from.
10 * @param refetchMode - Defines how re-fetches are handled.
11 * Defaults to `'reset'`, erases all data and puts the query back into `pending` state.
12 * Set to `'append'` to append new data to the existing data.
13 * Set to `'replace'` to write all data to the cache once the stream ends.
14 * @param maxChunks - The maximum number of chunks to keep in the cache.
15 * Defaults to `undefined`, meaning all chunks will be kept.
16 * If `undefined` or `0`, the number of chunks is unlimited.
17 * If the number of chunks exceeds this number, the oldest chunk will be removed.
18 */
19export function streamedQuery<
20 TQueryFnData = unknown,
21 TQueryKey extends QueryKey = QueryKey,
22>({
23 queryFn,
24 refetchMode = 'reset',
25 maxChunks,
26}: {
27 queryFn: (
28 context: QueryFunctionContext<TQueryKey>,
29 ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>
30 refetchMode?: 'append' | 'reset' | 'replace'
31 maxChunks?: number
32}): QueryFunction<Array<TQueryFnData>, TQueryKey> {
33 return async (context) => {
34 const query = context.client
35 .getQueryCache()
36 .find({ queryKey: context.queryKey, exact: true })
37 const isRefetch = !!query && query.state.data !== undefined
38​
39 if (isRefetch && refetchMode === 'reset') {
40 query.setState({
41 status: 'pending',
42 data: undefined,
43 error: null,
44 fetchStatus: 'fetching',
45 })
46 }
47​
48 let result: Array<TQueryFnData> = []
49 const stream = await queryFn(context)
50​
51 for await (const chunk of stream) {
52 if (context.signal.aborted) {
53 break
54 }
55​
56 // don't append to the cache directly when replace-refetching
57 if (!isRefetch || refetchMode !== 'replace') {
58 context.client.setQueryData<Array<TQueryFnData>>(
59 context.queryKey,
60 (prev = []) => {
61 return addToEnd(prev, chunk, maxChunks)
62 },
63 )
64 }
65 result = addToEnd(result, chunk, maxChunks)
66 }
67​
68 // finalize result: replace-refetching needs to write to the cache
69 if (isRefetch && refetchMode === 'replace' && !context.signal.aborted) {
70 context.client.setQueryData<Array<TQueryFnData>>(context.queryKey, result)
71 }
72​
73 return context.client.getQueryData(context.queryKey)!
74 }