Open History to see the last commit
1import { addConsumeAwareSignal, addToEnd } from './utils'
2import type {
3 OmitKeyof,
4 QueryFunction,
5 QueryFunctionContext,
6 QueryKey,
7} from './types'
8β
9type BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {
10 /** The function that returns an `AsyncIterable` to stream data from. */
11 streamFn: (
12 context: QueryFunctionContext<TQueryKey>,
13 ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>
14 /**
15 * Defines how refetches are handled.
16 * - `'reset'` (default): erases all data and puts the query back into `pending` state.
17 * - `'append'`: appends new data to the existing data.
18 * - `'replace'`: writes all data to the cache once the stream ends.
19 */
20 refetchMode?: 'append' | 'reset' | 'replace'
21}
22β
23type SimpleStreamedQueryParams<
24 TQueryFnData,
25 TQueryKey extends QueryKey,
26> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {
27 reducer?: never
28 initialValue?: never
29}
30β
31type ReducibleStreamedQueryParams<
32 TQueryFnData,
33 TData,
34 TQueryKey extends QueryKey,
35> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {
36 /**
37 * Reduces streamed chunks into the final data shape. Required whenever `TData` is not an
38 * array, since there is no default way to accumulate non-array chunks.
39 */
40 reducer: (acc: TData, chunk: TQueryFnData) => TData
41 /**
42 * The value used while the first chunk is being fetched, and returned if the stream yields no
43 * values. Required together with a custom `reducer`.
44 */
45 initialValue: TData
46}
47β
48type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =
49 | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>
50 | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>
51β
52/**
53 * This is a helper function to create a query function that streams data from an AsyncIterable.
54 * Data will be an Array of all the chunks received.
55 * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
56 * The query will stay in fetchStatus 'fetching' until the stream ends.
57 * @param streamFn - The function that returns an AsyncIterable to stream data from.
58 * @param refetchMode - Defines how re-fetches are handled.
59 * Defaults to `'reset'`, erases all data and puts the query back into `pending` state.
60 * Set to `'append'` to append new data to the existing data.
61 * Set to `'replace'` to write all data to the cache once the stream ends.
62 * @param reducer - A function to reduce the streamed chunks into the final data.
63 * Defaults to a function that appends chunks to the end of the array.
64 * @param initialValue - Initial value to be used while the first chunk is being fetched, and returned if the stream yields no values.
65 * @example
66 * ```ts
67 * await queryClient.query({
68 * queryKey: ['data'],
69 * queryFn: streamedQuery({
70 * streamFn: fetchDataInChunks,
71 * }),
72 * })
73 * ```
74 */
75export function streamedQuery<
76 TQueryFnData = unknown,
77 TData = Array<TQueryFnData>,
78 TQueryKey extends QueryKey = QueryKey,
79>({
80 streamFn,
81 refetchMode = 'reset',
82 reducer = (items, chunk) =>
83 addToEnd(items as Array<TQueryFnData>, chunk) as TData,
84 initialValue = [] as TData,
85}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<
86 TData,
87 TQueryKey
88> {
89 return async (context) => {
90 const query = context.client
91 .getQueryCache()
92 .find({ queryKey: context.queryKey, exact: true })
93 const isRefetch = !!query && query.isFetched()
94 if (isRefetch && refetchMode === 'reset') {
95 query.setState({
96 ...query.resetState,
97 fetchStatus: 'fetching',
98 })
99 }
100β
101 let result = initialValue
102β
103 let cancelled: boolean = false as boolean
104 const streamFnContext = addConsumeAwareSignal<
105 OmitKeyof<typeof context, 'signal'>
106 >(
107 {
108 client: context.client,
109 meta: context.meta,
110 queryKey: context.queryKey,
111 pageParam: context.pageParam,
112 direction: context.direction,
113 },
114 () => context.signal,
115 () => (cancelled = true),
116 )
117β
118 const stream = await streamFn(streamFnContext)
119β
120 const isReplaceRefetch = isRefetch && refetchMode === 'replace'
121β
122 for await (const chunk of stream) {
123 if (cancelled) {
124 break
125 }
126β
127 if (isReplaceRefetch) {
128 // don't append to the cache directly when replace-refetching
129 result = reducer(result, chunk)
130 } else {
131 context.client.setQueryData<TData>(context.queryKey, (prev) =>
132 reducer(prev === undefined ? initialValue : prev, chunk),
133 )
134 }
135 }
136β
137 // finalize result: replace-refetching needs to write to the cache
138 if (isReplaceRefetch && !cancelled) {
139 context.client.setQueryData<TData>(context.queryKey, result)
140 }
141β
142 const data = context.client.getQueryData<TData>(context.queryKey)
143 return data === undefined ? initialValue : data
144 }
145}