リクエストコンテキスト
非公式ベータ版翻訳
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
createContext()関数は各リクエストごとに呼び出され、その結果はすべてのリゾルバに伝搬されます。これを使用して、コンテキストデータをリゾルバに渡すことができます。
コード例
server/context.tstsimport * as trpc from '@trpc/server';import * as trpcNext from '@trpc/server/adapters/next';// The app's context - is generated for each incoming requestexport 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 fnasync 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 contextexport function createRouter() {return trpc.router<Context>();}
server/context.tstsimport * as trpc from '@trpc/server';import * as trpcNext from '@trpc/server/adapters/next';// The app's context - is generated for each incoming requestexport 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 fnasync 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 contextexport function createRouter() {return trpc.router<Context>();}