UNPKG

@trpc/tanstack-react-query

Version:

TanStack React Query Integration for tRPC

1 lines • 7.97 kB
{"version":3,"file":"utils-DTVvWT-Z.mjs","names":["streamedQuery"],"sources":["../src/internals/utils.ts"],"sourcesContent":["import {\n skipToken,\n experimental_streamedQuery as streamedQuery,\n type QueryClient,\n type QueryFunctionContext,\n type QueryKey,\n} from '@tanstack/react-query';\nimport {\n isFunction,\n isObject,\n run,\n} from '@trpc/server/unstable-core-do-not-import';\nimport type {\n AnyTRPCMutationKey,\n AnyTRPCQueryKey,\n FeatureFlags,\n QueryType,\n TRPCMutationKeyWithoutPrefix,\n TRPCQueryKey,\n TRPCQueryKeyWithoutPrefix,\n TRPCQueryKeyWithPrefix,\n TRPCQueryOptionsResult,\n} from './types';\n\n/**\n * @internal\n */\nexport function createTRPCOptionsResult(value: {\n path: string[];\n}): TRPCQueryOptionsResult['trpc'] {\n const path = value.path.join('.');\n\n return {\n path,\n };\n}\n\nexport function isPrefixedQueryKey(\n queryKey: TRPCQueryKey<any>,\n): queryKey is TRPCQueryKeyWithPrefix {\n return queryKey.length >= 3;\n}\n\nexport function readQueryKey(queryKey: AnyTRPCQueryKey) {\n if (isPrefixedQueryKey(queryKey)) {\n return {\n type: 'prefixed' as const,\n prefix: queryKey[0],\n path: queryKey[1],\n args: queryKey[2],\n };\n } else {\n return {\n type: 'unprefixed' as const,\n prefix: undefined,\n path: queryKey[0],\n args: queryKey[1],\n };\n }\n}\n\n/**\n * @internal\n */\nexport function getClientArgs<TOptions, TFeatureFlags extends FeatureFlags>(\n queryKey: TRPCQueryKey<TFeatureFlags['keyPrefix']>,\n opts: TOptions,\n infiniteParams?: {\n pageParam: any;\n direction: 'forward' | 'backward';\n },\n) {\n const queryKeyData = readQueryKey(queryKey);\n\n let input = queryKeyData.args?.input;\n if (infiniteParams) {\n input = {\n ...(queryKeyData.args?.input ?? {}),\n ...(infiniteParams.pageParam !== undefined\n ? { cursor: infiniteParams.pageParam }\n : {}),\n direction: infiniteParams.direction,\n };\n }\n return [queryKeyData.path.join('.'), input, (opts as any)?.trpc] as const;\n}\n\n/**\n * Streams a procedure's async iterable into the query with TanStack Query's\n * `streamedQuery`, which stops writing to the cache once the fetch is\n * cancelled or replaced by a refetch.\n * @internal\n */\nexport async function streamIntoQuery(opts: {\n iterable: AsyncIterable<unknown>;\n context: QueryFunctionContext<QueryKey>;\n queryClient: QueryClient;\n /** Aborts the request, for a stream that isn't read to the end. */\n abortController: AbortController;\n}) {\n // a context built by hand can lack `client`; a real one is passed as is, as\n // spreading it would read `signal` and make unmounting cancel the query\n const context = opts.context.client\n ? opts.context\n : { ...opts.context, client: opts.queryClient };\n let finished = false;\n const { iterable } = opts;\n async function* readToEnd() {\n yield* iterable;\n finished = true;\n }\n try {\n return await streamedQuery<unknown>({ streamFn: readToEnd })(context);\n } finally {\n // `streamedQuery` stops reading, or never starts, once the fetch is\n // cancelled: abort the request so the server stops streaming too\n if (!finished) {\n opts.abortController.abort();\n }\n }\n}\n\n/**\n * To allow easy interactions with groups of related queries, such as\n * invalidating all queries of a router, we use an array as the path when\n * storing in tanstack query.\n *\n * @internal\n */\nexport function getQueryKeyInternal(opts: {\n path: string[];\n input?: unknown;\n type: QueryType;\n prefix: string | undefined;\n}): AnyTRPCQueryKey {\n const key = run((): TRPCQueryKeyWithoutPrefix => {\n const { input, type } = opts;\n\n // Construct a query key that is easy to destructure and flexible for\n // partial selecting etc.\n // https://github.com/trpc/trpc/issues/3128\n\n // some parts of the path may be dot-separated, split them up\n const splitPath = opts.path.flatMap((part) => part.split('.'));\n\n if (typeof input === 'undefined' && type === 'any') {\n // this matches also all mutations (see `getMutationKeyInternal`)\n\n // for `utils.invalidate()` to match all queries (including vanilla react-query)\n // we don't want nested array if path is empty, i.e. `[]` instead of `[[]]`\n return splitPath.length ? [splitPath] : ([] as unknown as TRPCQueryKey);\n }\n\n if (\n type === 'infinite' &&\n isObject(input) &&\n ('direction' in input || 'cursor' in input)\n ) {\n const {\n cursor: _,\n direction: __,\n ...inputWithoutCursorAndDirection\n } = input;\n return [\n splitPath,\n {\n input: inputWithoutCursorAndDirection,\n type: 'infinite',\n },\n ];\n }\n\n return [\n splitPath,\n {\n ...(typeof input !== 'undefined' &&\n input !== skipToken && { input: input }),\n ...(type && type !== 'any' && { type: type }),\n },\n ];\n });\n\n if (opts.prefix) {\n key.unshift([opts.prefix]);\n }\n return key;\n}\n\n/**\n * @internal\n */\nexport function getMutationKeyInternal(opts: {\n prefix: string | undefined;\n path: string[];\n}): AnyTRPCMutationKey {\n // some parts of the path may be dot-separated, split them up\n const key: TRPCMutationKeyWithoutPrefix = [\n opts.path.flatMap((part) => part.split('.')),\n ];\n\n if (opts.prefix) {\n key.unshift([opts.prefix]);\n }\n return key;\n}\n\n/**\n * @internal\n */\nexport function unwrapLazyArg<T>(valueOrLazy: T | (() => T)): T {\n return (isFunction(valueOrLazy) ? valueOrLazy() : valueOrLazy) as T;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+JQ,MAAA,YAAA,CAAA,UACA,WAAA;;;;AArIR,SAAgB,wBAAwB,OAEL;CAGjC,OAAO,EACL,MAHW,MAAM,KAAK,KAAK,GAGxB,EACL;AACF;AAEA,SAAgB,mBACd,UACoC;CACpC,OAAO,SAAS,UAAU;AAC5B;AAEA,SAAgB,aAAa,UAA2B;CACtD,IAAI,mBAAmB,QAAQ,GAC7B,OAAO;EACL,MAAM;EACN,QAAQ,SAAS;EACjB,MAAM,SAAS;EACf,MAAM,SAAS;CACjB;MAEA,OAAO;EACL,MAAM;EACN,QAAQ,KAAA;EACR,MAAM,SAAS;EACf,MAAM,SAAS;CACjB;AAEJ;;;;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