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 * @example
59 * ```ts
60 * await queryClient.query({
61 * queryKey: ['data'],
62 * queryFn: streamedQuery({
63 * streamFn: fetchDataInChunks,
64 * }),
65 * })
66 * ```
67 */
68export function streamedQuery<
69 TQueryFnData = unknown,
70 TData = Array<TQueryFnData>,
71 TQueryKey extends QueryKey = QueryKey,
72>({
73 streamFn,
74 refetchMode = 'reset',
75 reducer = (items, chunk) =>
76 addToEnd(items as Array<TQueryFnData>, chunk) as TData,
77 initialValue = [] as TData,
78}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<
79 TData,
80 TQueryKey
81> {
82 return async (context) => {
83 const query = context.client
84 .getQueryCache()
85 .find({ queryKey: context.queryKey, exact: true })
86 const isRefetch = !!query && query.isFetched()
87 if (isRefetch && refetchMode === 'reset') {
88 query.setState({
89 ...query.resetState,
90 fetchStatus: 'fetching',
91 })
92 }
93β
94 let result = initialValue
95β
96 let cancelled: boolean = false as boolean
97 const streamFnContext = addConsumeAwareSignal<
98 OmitKeyof<typeof context, 'signal'>
99 >(
100 {
101 client: context.client,
102 meta: context.meta,
103 queryKey: context.queryKey,
104 pageParam: context.pageParam,
105 direction: context.direction,
106 },
107 () => context.signal,
108 () => (cancelled = true),
109 )
110β
111 const stream = await streamFn(streamFnContext)
112β
113 const isReplaceRefetch = isRefetch && refetchMode === 'replace'
114β
115 for await (const chunk of stream) {
116 if (cancelled) {
117 break
118 }
119β
120 if (isReplaceRefetch) {
121 // don't append to the cache directly when replace-refetching
122 result = reducer(result, chunk)
123 } else {
124 context.client.setQueryData<TData>(context.queryKey, (prev) =>
125 reducer(prev === undefined ? initialValue : prev, chunk),
126 )
127 }
128 }
129β
130 // finalize result: replace-refetching needs to write to the cache
131 if (isReplaceRefetch && !cancelled) {
132 context.client.setQueryData<TData>(context.queryKey, result)
133 }
134β
135 const data = context.client.getQueryData<TData>(context.queryKey)
136 return data === undefined ? initialValue : data
137 }
138}