src/server/api/trpc.ts
此代码来自构建时的仓库快照。修改源码后重新构建即可更新。
import { initTRPC, TRPCError } from '@trpc/server';
import { ZodError } from 'zod';
import type { PrismaClient } from '@/generated/prisma/client';
// userId 只能来自 Better Auth 校验后的 Cookie 会话,不接收客户端自报身份。
export type ApiContext = { db: PrismaClient; userId: string | null };
export const t = initTRPC.context<ApiContext>().create({
errorFormatter({ shape, error }) {
return {
...shape,
message:
error.code === 'INTERNAL_SERVER_ERROR'
? '服务暂不可用,请稍后重试'
: shape.message,
data: {
...shape.data,
stack: undefined,
zodError:
error.cause instanceof ZodError ? error.cause.flatten() : null,
},
};
},
});
export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
if (!ctx.userId)
throw new TRPCError({ code: 'UNAUTHORIZED', message: '请先登录' });
return next({ ctx: { ...ctx, userId: ctx.userId } });
});