Open History to see the last commit
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 - Defaults to 'reset', which replaces data when a refetch happens. Set to 'append' to append new data to the existing data.
10 */
11export function streamedQuery<
12 TQueryFnData = unknown,
13 TQueryKey extends QueryKey = QueryKey,
14>({
15 queryFn,
16 refetchMode,
17}: {
18 queryFn: (
19 context: QueryFunctionContext<TQueryKey>,
20 ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>
21 refetchMode?: 'append' | 'reset'
22}): QueryFunction<Array<TQueryFnData>, TQueryKey> {
23 return async (context) => {
24 if (refetchMode !== 'append') {
25 const query = context.client
26 .getQueryCache()
27 .find({ queryKey: context.queryKey, exact: true })
28 if (query && query.state.data !== undefined) {
29 query.setState({
30 status: 'pending',
31 data: undefined,
32 error: null,
33 fetchStatus: 'fetching',
34 })
35 }
36 }
37 const stream = await queryFn(context)
38 for await (const chunk of stream) {
39 if (context.signal.aborted) {
40 break
41 }
42 context.client.setQueryData<Array<TQueryFnData>>(
43 context.queryKey,
44 (prev = []) => {
45 return prev.concat(chunk)
46 },
47 )
48 }
49 return context.client.getQueryData(context.queryKey)!
50 }
51}