响应缓存
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
以下示例使用 Vercel 的边缘缓存 以最快速度向用户提供数据。
信息
使用缓存时务必谨慎——尤其是在处理个人信息时。
由于默认启用了批处理,建议在 responseMeta 函数中设置缓存头部,并确保没有可能包含个人数据的并发调用——或者当存在认证头或 cookie 时完全省略缓存头部。
你也可以使用 splitLink 来区分公共请求和需要保持私有且不缓存的请求。
应用缓存
若在应用中启用 SSR,可能会发现应用在 Vercel 等平台加载缓慢,实际上无需 SSG 也能静态渲染整个应用;参阅此 Twitter 讨论串获取更多洞见。
示例代码
utils/trpc.tsxtsximport { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';import type { AppRouter } from '../server/routers/_app';export const trpc = createTRPCNext<AppRouter>({config(config) {if (typeof window !== 'undefined') {return {links: [httpBatchLink({url: '/api/trpc',}),],};}const url = process.env.VERCEL_URL? `https://${process.env.VERCEL_URL}/api/trpc`: 'http://localhost:3000/api/trpc';return {links: {http: httpBatchLink({url,}),},};},ssr: true,responseMeta(opts) {const { clientErrors } = opts;if (clientErrors.length) {// propagate http first error from API callsreturn {status: clientErrors[0].data?.httpStatus ?? 500,};}// cache request for 1 day + revalidate once every secondconst ONE_DAY_IN_SECONDS = 60 * 60 * 24;return {headers: {'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,},};},});
utils/trpc.tsxtsximport { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';import type { AppRouter } from '../server/routers/_app';export const trpc = createTRPCNext<AppRouter>({config(config) {if (typeof window !== 'undefined') {return {links: [httpBatchLink({url: '/api/trpc',}),],};}const url = process.env.VERCEL_URL? `https://${process.env.VERCEL_URL}/api/trpc`: 'http://localhost:3000/api/trpc';return {links: {http: httpBatchLink({url,}),},};},ssr: true,responseMeta(opts) {const { clientErrors } = opts;if (clientErrors.length) {// propagate http first error from API callsreturn {status: clientErrors[0].data?.httpStatus ?? 500,};}// cache request for 1 day + revalidate once every secondconst ONE_DAY_IN_SECONDS = 60 * 60 * 24;return {headers: {'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,},};},});
API 响应缓存
由于所有查询都是标准的 HTTP GET 请求,我们可以使用常规 HTTP 头部缓存响应,从而加速响应、减轻数据库压力,并轻松将 API 扩展到海量用户。
使用 responseMeta 缓存响应
假设你将 API 部署在支持处理 stale-while-revalidate 缓存头的地方(例如 Vercel)。
server.tstsximport { initTRPC } from '@trpc/server';import * as trpcNext from '@trpc/server/adapters/next';export const createContext = async ({req,res,}: trpcNext.CreateNextContextOptions) => {return {req,res,prisma,};};type Context = Awaited<ReturnType<typeof createContext>>;export const t = initTRPC.context<Context>().create();const waitFor = async (ms: number) =>new Promise((resolve) => setTimeout(resolve, ms));export const appRouter = t.router({public: t.router({slowQueryCached: t.procedure.query(async (opts) => {await waitFor(5000); // wait for 5sreturn {lastUpdated: new Date().toJSON(),};}),}),});// Exporting type _type_ AppRouter only exposes types that can be used for inference// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-exportexport type AppRouter = typeof appRouter;// export API handlerexport default trpcNext.createNextApiHandler({router: appRouter,createContext,responseMeta(opts) {const { ctx, paths, errors, type } = opts;// assuming you have all your public routes with the keyword `public` in themconst allPublic = paths && paths.every((path) => path.includes('public'));// checking that no procedures erroredconst allOk = errors.length === 0;// checking we're doing a query requestconst isQuery = type === 'query';if (ctx?.res && allPublic && allOk && isQuery) {// cache request for 1 day + revalidate once every secondconst ONE_DAY_IN_SECONDS = 60 * 60 * 24;return {headers: {'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,},};}return {};},});
server.tstsximport { initTRPC } from '@trpc/server';import * as trpcNext from '@trpc/server/adapters/next';export const createContext = async ({req,res,}: trpcNext.CreateNextContextOptions) => {return {req,res,prisma,};};type Context = Awaited<ReturnType<typeof createContext>>;export const t = initTRPC.context<Context>().create();const waitFor = async (ms: number) =>new Promise((resolve) => setTimeout(resolve, ms));export const appRouter = t.router({public: t.router({slowQueryCached: t.procedure.query(async (opts) => {await waitFor(5000); // wait for 5sreturn {lastUpdated: new Date().toJSON(),};}),}),});// Exporting type _type_ AppRouter only exposes types that can be used for inference// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html#type-only-imports-and-exportexport type AppRouter = typeof appRouter;// export API handlerexport default trpcNext.createNextApiHandler({router: appRouter,createContext,responseMeta(opts) {const { ctx, paths, errors, type } = opts;// assuming you have all your public routes with the keyword `public` in themconst allPublic = paths && paths.every((path) => path.includes('public'));// checking that no procedures erroredconst allOk = errors.length === 0;// checking we're doing a query requestconst isQuery = type === 'query';if (ctx?.res && allPublic && allOk && isQuery) {// cache request for 1 day + revalidate once every secondconst ONE_DAY_IN_SECONDS = 60 * 60 * 24;return {headers: {'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,},};}return {};},});