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

streamedQuery.ts

122 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.state.data !== undefined
70 if (isRefetch && refetchMode === 'reset') {
71 query.setState({
72 status: 'pending',
73 data: undefined,
74 error: null,
75 fetchStatus: 'fetching',
76 })
77 }
78​
79 let result = initialValue
80​
81 let cancelled: boolean = false as boolean
82 const streamFnContext = addConsumeAwareSignal<
83 OmitKeyof<typeof context, 'signal'>
84 >(
85 {
86 client: context.client,
87 meta: context.meta,
88 queryKey: context.queryKey,
89 pageParam: context.pageParam,
90 direction: context.direction,
91 },
92 () => context.signal,
93 () => (cancelled = true),
94 )
95​
96 const stream = await streamFn(streamFnContext)
97​
98 const isReplaceRefetch = isRefetch && refetchMode === 'replace'
99​
100 for await (const chunk of stream) {
101 if (cancelled) {
102 break
103 }
104​
105 if (isReplaceRefetch) {
106 // don't append to the cache directly when replace-refetching
107 result = reducer(result, chunk)
108 } else {
109 context.client.setQueryData<TData>(context.queryKey, (prev) =>
110 reducer(prev === undefined ? initialValue : prev, chunk),
111 )
112 }
113 }
114​
115 // finalize result: replace-refetching needs to write to the cache
116 if (isReplaceRefetch && !cancelled) {
117 context.client.setQueryData<TData>(context.queryKey, result)
118 }
119​
120 return context.client.getQueryData(context.queryKey) ?? initialValue
121 }