UNPKG

@trpc/tanstack-react-query

Version:

TanStack React Query Integration for tRPC

353 lines (352 loc) • 13.6 kB
import { c as _objectSpread2, i as getQueryKeyInternal, n as getClientArgs, o as streamIntoQuery, r as getMutationKeyInternal, s as unwrapLazyArg, t as createTRPCOptionsResult } from "./utils-DTVvWT-Z.mjs"; import * as React from "react"; import { TRPCUntypedClient, getUntypedClient } from "@trpc/client"; import { callTRPCProcedure, createTRPCRecursiveProxy } from "@trpc/server"; import { HydrationBoundary, defaultShouldDehydrateMutation, defaultShouldDehydrateQuery, dehydrate, infiniteQueryOptions, queryOptions, skipToken } from "@tanstack/react-query"; import { isAsyncIterable } from "@trpc/server/unstable-core-do-not-import"; // src/internals/infiniteQueryOptions.ts function trpcInfiniteQueryOptions(args) { var _opts$initialCursor; const { input, query, path, queryKey, opts } = args; const inputIsSkipToken = input === skipToken; const queryFn = async (queryFnContext) => { var _opts$trpc; const actualOpts = _objectSpread2(_objectSpread2({}, opts), {}, { trpc: _objectSpread2(_objectSpread2({}, opts === null || opts === void 0 ? void 0 : opts.trpc), (opts === null || opts === void 0 || (_opts$trpc = opts.trpc) === null || _opts$trpc === void 0 ? void 0 : _opts$trpc.abortOnUnmount) ? { signal: queryFnContext.signal } : { signal: null }) }); return await query(...getClientArgs(queryKey, actualOpts, { direction: queryFnContext.direction, pageParam: queryFnContext.pageParam })); }; return Object.assign(infiniteQueryOptions(_objectSpread2(_objectSpread2({}, opts !== null && opts !== void 0 ? opts : {}), {}, { queryKey, queryFn: inputIsSkipToken ? skipToken : queryFn, initialPageParam: (_opts$initialCursor = opts === null || opts === void 0 ? void 0 : opts.initialCursor) !== null && _opts$initialCursor !== void 0 ? _opts$initialCursor : input === null || input === void 0 ? void 0 : input.cursor })), { trpc: createTRPCOptionsResult({ path }) }); } // src/internals/mutationOptions.ts /** * @internal */ function trpcMutationOptions(args) { var _opts$keyPrefix, _overrides$onSuccess; const { mutate, path, prefix, opts, overrides } = args; const queryClient = unwrapLazyArg(args.queryClient); const mutationKey = getMutationKeyInternal({ path, prefix: (_opts$keyPrefix = opts === null || opts === void 0 ? void 0 : opts.keyPrefix) !== null && _opts$keyPrefix !== void 0 ? _opts$keyPrefix : prefix }); const defaultOpts = queryClient.defaultMutationOptions(queryClient.getMutationDefaults(mutationKey)); const mutationSuccessOverride = (_overrides$onSuccess = overrides === null || overrides === void 0 ? void 0 : overrides.onSuccess) !== null && _overrides$onSuccess !== void 0 ? _overrides$onSuccess : ((options) => options.originalFn()); const mutationFn = async (input) => { return await mutate(...getClientArgs([...mutationKey, { input }], opts)); }; return _objectSpread2(_objectSpread2({}, opts), {}, { mutationKey, mutationFn, onSuccess(...args) { var _ref, _opts$meta; const originalFn = () => { var _opts$onSuccess, _opts$onSuccess2, _defaultOpts$onSucces; return (_opts$onSuccess = opts === null || opts === void 0 || (_opts$onSuccess2 = opts.onSuccess) === null || _opts$onSuccess2 === void 0 ? void 0 : _opts$onSuccess2.call(opts, ...args)) !== null && _opts$onSuccess !== void 0 ? _opts$onSuccess : defaultOpts === null || defaultOpts === void 0 || (_defaultOpts$onSucces = defaultOpts.onSuccess) === null || _defaultOpts$onSucces === void 0 ? void 0 : _defaultOpts$onSucces.call(defaultOpts, ...args); }; return mutationSuccessOverride({ originalFn, queryClient, meta: (_ref = (_opts$meta = opts === null || opts === void 0 ? void 0 : opts.meta) !== null && _opts$meta !== void 0 ? _opts$meta : defaultOpts === null || defaultOpts === void 0 ? void 0 : defaultOpts.meta) !== null && _ref !== void 0 ? _ref : {} }); }, trpc: createTRPCOptionsResult({ path }) }); } // src/internals/queryOptions.ts /** * @internal */ function trpcQueryOptions(args) { const { input, query, path, queryKey, opts } = args; const queryClient = unwrapLazyArg(args.queryClient); const inputIsSkipToken = input === skipToken; const queryFn = async (queryFnContext) => { var _opts$trpc; const abortController = new AbortController(); const actualOpts = _objectSpread2(_objectSpread2({}, opts), {}, { trpc: _objectSpread2(_objectSpread2({}, opts === null || opts === void 0 ? void 0 : opts.trpc), (opts === null || opts === void 0 || (_opts$trpc = opts.trpc) === null || _opts$trpc === void 0 ? void 0 : _opts$trpc.abortOnUnmount) ? { signal: queryFnContext.signal } : { signal: abortController.signal }) }); const queryKey = queryFnContext.queryKey; const result = await query(...getClientArgs(queryKey, actualOpts)); if (isAsyncIterable(result)) return streamIntoQuery({ iterable: result, context: queryFnContext, queryClient, abortController }); return result; }; return Object.assign(queryOptions(_objectSpread2(_objectSpread2({}, opts), {}, { queryKey, queryFn: inputIsSkipToken ? skipToken : queryFn })), { trpc: createTRPCOptionsResult({ path }) }); } // src/internals/subscriptionOptions.ts /** * @internal */ const trpcSubscriptionOptions = (args) => { const { subscribe, path, queryKey, input, opts = {} } = args; const enabled = "enabled" in opts ? !!opts.enabled : input !== skipToken; const _subscribe = (innerOpts) => { return subscribe(path.join("."), input === skipToken ? void 0 : input, _objectSpread2(_objectSpread2({}, innerOpts), {}, { onComplete: () => { var _innerOpts$onComplete; return (_innerOpts$onComplete = innerOpts.onComplete) === null || _innerOpts$onComplete === void 0 ? void 0 : _innerOpts$onComplete.call(innerOpts); } })); }; return _objectSpread2(_objectSpread2({}, opts), {}, { enabled, subscribe: _subscribe, queryKey, trpc: createTRPCOptionsResult({ path }) }); }; // src/internals/createOptionsProxy.ts /** * Creates the options proxy without React context. Works on the server too. * * @example * ```ts * export const trpc = createTRPCOptionsProxy<AppRouter>({ * client: trpcClient, * queryClient, * }); * ``` * * @see https://trpc.io/docs/client/tanstack-react-query/setup#3c-set-up-without-react-context * @see https://trpc.io/docs/client/tanstack-react-query/server-components#5-create-a-trpc-caller-for-server-components */ function createTRPCOptionsProxy(opts) { const prefix = opts.keyPrefix; const callIt = (type) => { return (path, input, trpcOpts) => { if ("router" in opts) return Promise.resolve(unwrapLazyArg(opts.ctx)).then((ctx) => callTRPCProcedure({ router: opts.router, path, getRawInput: async () => input, ctx, type, signal: void 0, batchIndex: 0 })); return (opts.client instanceof TRPCUntypedClient ? opts.client : getUntypedClient(opts.client))[type](path, input, trpcOpts); }; }; return createTRPCRecursiveProxy(({ args, path: _path }) => { const path = [..._path]; const utilName = path.pop(); const [arg1, arg2] = args; return { "~types": void 0, "~queryClient": () => unwrapLazyArg(opts.queryClient), pathKey: () => { return getQueryKeyInternal({ path, type: "any", prefix }); }, pathFilter: () => { return _objectSpread2(_objectSpread2({}, arg1), {}, { queryKey: getQueryKeyInternal({ path, type: "any", prefix }) }); }, queryOptions: () => { return trpcQueryOptions({ input: arg1, opts: arg2, path, queryClient: opts.queryClient, queryKey: getQueryKeyInternal({ path, input: arg1, type: "query", prefix }), query: callIt("query") }); }, queryKey: () => { return getQueryKeyInternal({ path, input: arg1, type: "query", prefix }); }, queryFilter: () => { return _objectSpread2(_objectSpread2({}, arg2), {}, { queryKey: getQueryKeyInternal({ path, input: arg1, type: "query", prefix }) }); }, infiniteQueryOptions: () => { return trpcInfiniteQueryOptions({ input: arg1, opts: arg2, path, queryClient: opts.queryClient, queryKey: getQueryKeyInternal({ path, input: arg1, type: "infinite", prefix }), query: callIt("query") }); }, infiniteQueryKey: () => { return getQueryKeyInternal({ path, input: arg1, type: "infinite", prefix }); }, infiniteQueryFilter: () => { return _objectSpread2(_objectSpread2({}, arg2), {}, { queryKey: getQueryKeyInternal({ path, input: arg1, type: "infinite", prefix }) }); }, mutationOptions: () => { var _opts$overrides; return trpcMutationOptions({ opts: arg1, path, prefix, queryClient: opts.queryClient, mutate: callIt("mutation"), overrides: (_opts$overrides = opts.overrides) === null || _opts$overrides === void 0 ? void 0 : _opts$overrides.mutations }); }, mutationKey: () => { return getMutationKeyInternal({ path, prefix }); }, subscriptionOptions: () => { return trpcSubscriptionOptions({ opts: arg2, path, input: arg1, queryKey: getQueryKeyInternal({ path, input: arg1, type: "any", prefix }), subscribe: callIt("subscription") }); } }[utilName](); }); } // src/internals/hydration.ts /** * Keyed by the request's `QueryClient`, so one server render's boundaries * share it and the next request starts over. */ const sentByClient = /* @__PURE__ */ new WeakMap(); function sentEntries(queryClient) { let sent = sentByClient.get(queryClient); if (!sent) { sent = { queries: /* @__PURE__ */ new Map(), mutations: /* @__PURE__ */ new WeakSet(), watchingPending: false }; sentByClient.set(queryClient, sent); } return sent; } /** * A query sent pending carries its request's promise, so the data that * request writes is already on its way. Record it once it lands: the query * drops its promise after settling, so it can't be compared later. */ function watchPendingSends(queryClient, sent) { if (sent.watchingPending) return; sent.watchingPending = true; queryClient.getQueryCache().subscribe((event) => { if (event.type !== "updated" || event.action.type !== "success" || event.action.manual) return; const entry = sent.queries.get(event.query.queryHash); if ((entry === null || entry === void 0 ? void 0 : entry.promise) && entry.promise === event.query.promise) { entry.dataUpdatedAt = event.query.state.dataUpdatedAt; entry.promise = void 0; } }); } function isAlreadySent(query, sent) { return sent !== void 0 && query.state.dataUpdatedAt <= sent.dataUpdatedAt; } /** * Dehydrate what the client's `dehydrate` defaults select, minus entries an * earlier call already sent for this client with the same or newer data. * @internal */ function dehydrateUnsent(queryClient) { var _defaults$shouldDehyd, _defaults$shouldDehyd2; const defaults = queryClient.getDefaultOptions().dehydrate; const shouldDehydrateQuery = (_defaults$shouldDehyd = defaults === null || defaults === void 0 ? void 0 : defaults.shouldDehydrateQuery) !== null && _defaults$shouldDehyd !== void 0 ? _defaults$shouldDehyd : defaultShouldDehydrateQuery; const shouldDehydrateMutation = (_defaults$shouldDehyd2 = defaults === null || defaults === void 0 ? void 0 : defaults.shouldDehydrateMutation) !== null && _defaults$shouldDehyd2 !== void 0 ? _defaults$shouldDehyd2 : defaultShouldDehydrateMutation; const sent = sentEntries(queryClient); return dehydrate(queryClient, { shouldDehydrateQuery: (query) => { if (isAlreadySent(query, sent.queries.get(query.queryHash)) || !shouldDehydrateQuery(query)) return false; const promise = query.state.status === "pending" ? query.promise : void 0; if (promise) watchPendingSends(queryClient, sent); sent.queries.set(query.queryHash, { dataUpdatedAt: query.state.dataUpdatedAt, promise }); return true; }, shouldDehydrateMutation: (mutation) => { if (sent.mutations.has(mutation) || !shouldDehydrateMutation(mutation)) return false; sent.mutations.add(mutation); return true; } }); } // src/internals/HydrateClient.tsx /** * Create a `HydrateClient` server component for the request's `QueryClient`. * It sends the queries started so far in this request to the browser, * pending ones as promises that stream in as they settle. A query an earlier * `HydrateClient` already sent is skipped, so nesting them is fine. * * React Server Components only: the package resolves to the server build * through the `react-server` export condition. * * @see https://trpc.io/docs/client/tanstack-react-query/handles#hydrate-client */ function unstable_createHydrateClient(_queryClient) { function HydrateClient() { throw new Error("`HydrateClient` from `unstable_createHydrateClient()` works only in React Server Components. Render it from a server component; in client components, use TanStack Query's `HydrationBoundary`."); } return HydrateClient; } /** * `unstable_createHydrateClient` for the `react-server` export condition. * @internal */ function createHydrateClientReactServer(queryClient) { function HydrateClient(props) { return /* @__PURE__ */ React.createElement(HydrationBoundary, { state: dehydrateUnsent(unwrapLazyArg(queryClient)) }, props.children); } return HydrateClient; } export { unstable_createHydrateClient as n, createTRPCOptionsProxy as r, createHydrateClientReactServer as t }; //# sourceMappingURL=HydrateClient-CWZqtji9.mjs.map