响应缓存
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
以下示例使用 Vercel 的边缘缓存 来尽可能快速地为用户提供数据。
⚠️ 注意事项 ⚠️
使用缓存时务必小心——尤其是在处理个人信息的情况下。
由于默认启用了批处理,建议在 responseMeta 函数中设置缓存头,并确保没有可能包含个人数据的并发调用——或者如果存在认证头或 cookie,则完全省略缓存头。
你也可以使用 splitLink 来区分公开请求与需要保持私有且不缓存的请求。
应用缓存
如果在应用中开启 SSR,你可能会发现应用在例如 Vercel 上加载缓慢,但实际上无需使用 SSG 也能静态渲染整个应用;阅读此 Twitter 主题 了解更多见解。
示例代码
pages/_app.tsxtsxexport default withTRPC({config(config) {if (typeof window !== 'undefined') {return {url: '/api/trpc',};}const url = process.env.VERCEL_URL? `https://${process.env.VERCEL_URL}/api/trpc`: 'http://localhost:3000/api/trpc';return {url,};},ssr: true,responseMeta(config) {if (config.clientErrors.length) {// propagate http first error from API callsreturn {status: config.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}`,},};},})(MyApp);
pages/_app.tsxtsxexport default withTRPC({config(config) {if (typeof window !== 'undefined') {return {url: '/api/trpc',};}const url = process.env.VERCEL_URL? `https://${process.env.VERCEL_URL}/api/trpc`: 'http://localhost:3000/api/trpc';return {url,};},ssr: true,responseMeta(config) {if (config.clientErrors.length) {// propagate http first error from API callsreturn {status: config.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}`,},};},})(MyApp);
API 响应缓存
由于所有查询都是标准的 HTTP GET 请求,我们可以使用常规 HTTP 头来缓存响应,从而加快响应速度、减轻数据库压力,并轻松将 API 扩展到海量用户。
使用 responseMeta 缓存响应
假设你将 API 部署在支持处理 stale-while-revalidate 缓存头的地方(例如 Vercel)。
server.tstsximport * as trpc from '@trpc/server';import { inferAsyncReturnType } 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 = inferAsyncReturnType<typeof createContext>;export function createRouter() {return trpc.router<Context>();}const waitFor = async (ms: number) =>new Promise((resolve) => setTimeout(resolve, ms));export const appRouter = createRouter().query('public.slow-query-cached', {async resolve({ ctx }) {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({ ctx, paths, type, errors }) {// 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 * as trpc from '@trpc/server';import { inferAsyncReturnType } 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 = inferAsyncReturnType<typeof createContext>;export function createRouter() {return trpc.router<Context>();}const waitFor = async (ms: number) =>new Promise((resolve) => setTimeout(resolve, ms));export const appRouter = createRouter().query('public.slow-query-cached', {async resolve({ ctx }) {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({ ctx, paths, type, errors }) {// 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 {};},});