({
streamFn,
refetchMode = 'reset',
reducer = (items, chunk) =>
addToEnd(items as Array<TQueryFnData>, chunk) as TData,
initialValue = [] as TData,
}: StreamedQueryParams<TQueryFnData, TData, TQueryKey>)
| 44 | * @param initialValue - Initial value to be used while the first chunk is being fetched. |
| 45 | */ |
| 46 | export 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 | } |
no test coverage detected
searching dependent graphs…