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

streamedQuery.ts

147 lines4.4 KB

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