响应缓存
以下示例使用 Vercel 的边缘缓存 以尽可能快的速度为您的用户提供数据。
info
始终小心缓存 - 特别是如果您处理个人信息。
由于批处理默认情况下已启用,建议在 responseMeta
函数中设置您的缓存标头,并确保没有可能包含个人数据的并发调用 - 或者如果存在身份验证标头或 cookie,则完全省略缓存标头。
您也可以使用 splitLink
来拆分您的公共请求和那些应该私有且未缓存的请求。
应用程序缓存
如果您在应用程序中打开 SSR,您可能会发现您的应用程序在例如 Vercel 上加载速度很慢,但您实际上可以在不使用 SSG 的情况下静态渲染整个应用程序;阅读此 Twitter 线程 以获取更多见解。
示例代码
utils/trpc.tsxtsx
import { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';import type { AppRouter } from '../server/routers/_app';export const trpc = createTRPCNext<AppRouter>({config(opts) {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: new Headers([['cache-control',`s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,],]),};},});
utils/trpc.tsxtsx
import { httpBatchLink } from '@trpc/client';import { createTRPCNext } from '@trpc/next';import type { AppRouter } from '../server/routers/_app';export const trpc = createTRPCNext<AppRouter>({config(opts) {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: new Headers([['cache-control',`s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,],]),};},});
API 响应缓存
由于所有查询都是正常的 HTTP GET
,我们可以使用正常的 HTTP 标头来缓存响应,使响应变得快速,让您的数据库休息一下,并轻松地将您的 API 扩展到数十亿用户。
使用 responseMeta
来缓存响应
假设您将 API 部署到可以处理陈旧-同时-重新验证缓存标头(如 Vercel)的地方。
server.tstsx
import { 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://typescript.net.cn/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: new Headers([['cache-control',`s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,],]),};}return {};},});
server.tstsx
import { 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://typescript.net.cn/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: new Headers([['cache-control',`s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`,],]),};}return {};},});