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

streamedQuery.ts

140 lines4.3 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 * - `'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'
22​
23type SimpleStreamedQueryParams<
24 TQueryFnData,
25 TQueryKey extends QueryKey,
26> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {
27 reducer?: never
28 initialValue?: never
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
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 let cancelled = false as boolean
99 const streamFnContext = addConsumeAwareSignal<
100 OmitKeyof<typeof context, 'signal'>
101 >(
102 {
103 client: context.client,
104 meta: context.meta,
105 queryKey: context.queryKey,
106 pageParam: context.pageParam,
107 direction: context.direction,
108 },
109 () => context.signal,
110 () => (cancelled = true),
111 )
112​
113 const stream = await streamFn(streamFnContext)
114​
115 const isReplaceRefetch = isRefetch && refetchMode === 'replace'
116​
117 for await (const chunk of stream) {
118 if (cancelled) {
119 break
120 }
121​
122 if (isReplaceRefetch) {
123 // don't append to the cache directly when replace-refetching
124 result = reducer(result, chunk)
125 } else {
126 context.client.setQueryData<TData>(context.queryKey, (prev) =>
127 reducer(prev === undefined ? initialValue : prev, chunk),
128 )
129 }
130 }
131​
132 // finalize result: replace-refetching needs to write to the cache
133 if (isReplaceRefetch && !cancelled) {
134 context.client.setQueryData<TData>(context.queryKey, result)
135 }
136​
137 const data = context.client.getQueryData<TData>(context.queryKey)
138 return data === undefined ? initialValue : data
139 }