跳至主内容
版本:9.x

路由元数据

非官方测试版翻译

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

路由元数据允许您添加可选的、特定于路由的 meta 属性,该属性将在所有 middleware 函数参数中可用。

创建带有类型化元数据的路由器

jsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean
}
export const appRouter = trpc.router<Context, Meta>();
jsx
import * as trpc from '@trpc/server';
// [...]
interface Meta {
hasAuth: boolean
}
export const appRouter = trpc.router<Context, Meta>();

按路由认证设置示例

server.ts
tsx
import * 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 enabled
if (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.ts
tsx
import * 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 enabled
if (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`,
};
},
});