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

streamedQuery.ts

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