跳至主内容
版本:9.x

请求上下文

非官方测试版翻译

本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →

createContext() 函数会在每个请求中被调用,其执行结果将传递给所有解析器。您可以通过此机制将上下文数据传递给下游的解析器。

示例代码

server/context.ts
ts
import * as trpc from '@trpc/server';
import * as trpcNext from '@trpc/server/adapters/next';
// The app's context - is generated for each incoming request
export async function createContext(opts?: trpcNext.CreateNextContextOptions) {
// Create your context based on the request object
// Will be available as `ctx` in all your resolvers
// This is just an example of something you'd might want to do in your ctx fn
async function getUserFromHeader() {
if (opts?.req.headers.authorization) {
// const user = await decodeJwtToken(req.headers.authorization.split(' ')[1])
// return user;
}
return null;
}
const user = await getUserFromHeader();
return {
user,
};
}
type Context = trpc.inferAsyncReturnType<typeof createContext>;
// Helper function to create a router with your app's context
export function createRouter() {
return trpc.router<Context>();
}
server/context.ts
ts
import * as trpc from '@trpc/server';
import * as trpcNext from '@trpc/server/adapters/next';
// The app's context - is generated for each incoming request
export async function createContext(opts?: trpcNext.CreateNextContextOptions) {
// Create your context based on the request object
// Will be available as `ctx` in all your resolvers
// This is just an example of something you'd might want to do in your ctx fn
async function getUserFromHeader() {
if (opts?.req.headers.authorization) {
// const user = await decodeJwtToken(req.headers.authorization.split(' ')[1])
// return user;
}
return null;
}
const user = await getUserFromHeader();
return {
user,
};
}
type Context = trpc.inferAsyncReturnType<typeof createContext>;
// Helper function to create a router with your app's context
export function createRouter() {
return trpc.router<Context>();
}