Open History to see the last commit
1import { addToEnd } from './utils'
2import type { QueryFunction, QueryFunctionContext, QueryKey } from './types'
3β
4type BaseStreamedQueryParams<TQueryFnData, TQueryKey extends QueryKey> = {
5 streamFn: (
6 context: QueryFunctionContext<TQueryKey>,
7 ) => AsyncIterable<TQueryFnData> | Promise<AsyncIterable<TQueryFnData>>
8 refetchMode?: 'append' | 'reset' | 'replace'
9}
10β
11type SimpleStreamedQueryParams<
12 TQueryFnData,
13 TQueryKey extends QueryKey,
14> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {
15 reducer?: never
16 initialValue?: never
17}
18β
19type ReducibleStreamedQueryParams<
20 TQueryFnData,
21 TData,
22 TQueryKey extends QueryKey,
23> = BaseStreamedQueryParams<TQueryFnData, TQueryKey> & {
24 reducer: (acc: TData, chunk: TQueryFnData) => TData
25 initialValue: TData
26}
27β
28type StreamedQueryParams<TQueryFnData, TData, TQueryKey extends QueryKey> =
29 | SimpleStreamedQueryParams<TQueryFnData, TQueryKey>
30 | ReducibleStreamedQueryParams<TQueryFnData, TData, TQueryKey>
31β
32/**
33 * This is a helper function to create a query function that streams data from an AsyncIterable.
34 * Data will be an Array of all the chunks received.
35 * The query will be in a 'pending' state until the first chunk of data is received, but will go to 'success' after that.
36 * The query will stay in fetchStatus 'fetching' until the stream ends.
37 * @param queryFn - The function that returns an AsyncIterable to stream data from.
38 * @param refetchMode - Defines how re-fetches are handled.
39 * Defaults to `'reset'`, erases all data and puts the query back into `pending` state.
40 * Set to `'append'` to append new data to the existing data.
41 * Set to `'replace'` to write all data to the cache once the stream ends.
42 * @param reducer - A function to reduce the streamed chunks into the final data.
43 * Defaults to a function that appends chunks to the end of the array.
44 * @param initialValue - Initial value to be used while the first chunk is being fetched.
45 */
46export function streamedQuery<
47 TQueryFnData = unknown,
48 TData = Array<TQueryFnData>,
49 TQueryKey extends QueryKey = QueryKey,
50>({
51 streamFn,
52 refetchMode = 'reset',
53 reducer = (items, chunk) =>
54 addToEnd(items as Array<TQueryFnData>, chunk) as TData,
55 initialValue = [] as TData,
56}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>): QueryFunction<
57 TData,
58 TQueryKey
59> {
60 return async (context) => {
61 const query = context.client
62 .getQueryCache()
63 .find({ queryKey: context.queryKey, exact: true })
64 const isRefetch = !!query && query.state.data !== undefined
65 if (isRefetch && refetchMode === 'reset') {
66 query.setState({
67 status: 'pending',
68 data: undefined,
69 error: null,
70 fetchStatus: 'fetching',
71 })
72 }
73β
74 let result = initialValue
75β
76 const stream = await streamFn(context)
77β
78 for await (const chunk of stream) {
79 if (context.signal.aborted) {
80 break
81 }
82β
83 // don't append to the cache directly when replace-refetching
84 if (!isRefetch || refetchMode !== 'replace') {
85 context.client.setQueryData<TData>(context.queryKey, (prev) =>
86 reducer(prev === undefined ? initialValue : prev, chunk),
87 )
88 }
89 result = reducer(result, chunk)
90 }
91β
92 // finalize result: replace-refetching needs to write to the cache
93 if (isRefetch && refetchMode === 'replace' && !context.signal.aborted) {
94 context.client.setQueryData<TData>(context.queryKey, result)
95 }
96β
97 return context.client.getQueryData(context.queryKey)!
98 }
99}