路由元数据
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
路由元数据允许您添加可选的、特定于路由的 meta 属性,该属性将在所有 middleware 函数参数中可用。
创建带有类型化元数据的路由器
jsximport * as trpc from '@trpc/server';// [...]interface Meta {hasAuth: boolean}export const appRouter = trpc.router<Context, Meta>();
jsximport * as trpc from '@trpc/server';// [...]interface Meta {hasAuth: boolean}export const appRouter = trpc.router<Context, Meta>();
按路由认证设置示例
server.tstsximport * as trpc from '@trpc/server';// [...]interface Meta {hasAuth: boolean;}export const appRouter = trpc.router<Context, Meta>().middleware(async ({ meta, next, ctx }) => {// only check authorization if enabledif (meta?.hasAuth && !ctx.user) {throw new TRPCError({ code: 'UNAUTHORIZED' });}return next();}).query('hello', {meta: {hasAuth: false,},resolve({ ctx }) {return {greeting: `hello world`,};},}).query('protected-hello', {meta: {hasAuth: true,},resolve({ ctx }) {return {greeting: `hello world`,};},});
server.tstsximport * as trpc from '@trpc/server';// [...]interface Meta {hasAuth: boolean;}export const appRouter = trpc.router<Context, Meta>().middleware(async ({ meta, next, ctx }) => {// only check authorization if enabledif (meta?.hasAuth && !ctx.user) {throw new TRPCError({ code: 'UNAUTHORIZED' });}return next();}).query('hello', {meta: {hasAuth: false,},resolve({ ctx }) {return {greeting: `hello world`,};},}).query('protected-hello', {meta: {hasAuth: true,},resolve({ ctx }) {return {greeting: `hello world`,};},});