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

streamedQuery.ts

68 lines2.3 KB

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