UNPKG

@trpc/next

Version:

The tRPC Next.js library

63 lines (59 loc) 2.99 kB
'use strict'; var client = require('@trpc/client'); var unstableInternals = require('@trpc/client/unstable-internals'); var observable = require('@trpc/server/observable'); var unstableCoreDoNotImport = require('@trpc/server/unstable-core-do-not-import'); var cache = require('next/cache'); var shared = require('../shared.js'); // import "server-only"; // ts-prune-ignore-next function experimental_nextCacheLink(opts) { const transformer = unstableInternals.getTransformer(opts.transformer); return ()=>({ op })=>observable.observable((observer)=>{ const { path, input, type, context } = op; const cacheTag = shared.generateCacheTag(path, input); // Let per-request revalidate override global revalidate const requestRevalidate = typeof context['revalidate'] === 'number' || context['revalidate'] === false ? context['revalidate'] : undefined; const revalidate = requestRevalidate ?? opts.revalidate ?? false; const promise = opts.createContext().then(async (ctx)=>{ const callProc = async (_cachebuster)=>{ // // _cachebuster is not used by us but to make sure // // that calls with different tags are properly separated // // @link https://github.com/trpc/trpc/issues/4622 const procedureResult = await unstableCoreDoNotImport.callProcedure({ router: opts.router, path, getRawInput: async ()=>input, ctx: ctx, type, signal: undefined }); // We need to serialize cause the cache only accepts JSON return transformer.input.serialize(procedureResult); }; if (type === 'query') { return cache.unstable_cache(callProc, path.split('.'), { revalidate, tags: [ cacheTag ] })(cacheTag); } return callProc(); }).catch((cause)=>{ observer.error(client.TRPCClientError.from(cause)); }); promise.then((data)=>{ const transformedResult = transformer.output.deserialize(data); observer.next({ result: { data: transformedResult } }); observer.complete(); }).catch((cause)=>{ observer.error(client.TRPCClientError.from(cause)); }); }); } exports.experimental_nextCacheLink = experimental_nextCacheLink;