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