training_data/apps/server/src/trpc/trpc.service.ts

49 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-09-10 11:23:02 +08:00
import { Injectable, Logger } from '@nestjs/common';
2024-09-03 20:19:33 +08:00
import { initTRPC, TRPCError } from '@trpc/server';
2024-07-11 11:00:51 +08:00
import superjson from 'superjson-cjs';
2024-09-03 20:19:33 +08:00
import * as trpcExpress from '@trpc/server/adapters/express';
2024-12-30 08:26:40 +08:00
import { db, JwtPayload, UserProfile, RolePerms } from '@nicestack/common';
import { CreateWSSContextFnOptions } from '@trpc/server/adapters/ws';
import { UserProfileService } from '@server/auth/utils';
type Context = Awaited<ReturnType<TrpcService['createExpressContext']>>;
2024-07-11 11:00:51 +08:00
@Injectable()
export class TrpcService {
2024-12-30 08:26:40 +08:00
private readonly logger = new Logger(TrpcService.name);
2024-09-10 11:23:02 +08:00
2024-12-30 08:26:40 +08:00
async createExpressContext(opts: trpcExpress.CreateExpressContextOptions): Promise<{ staff: UserProfile | undefined }> {
const token = opts.req.headers.authorization?.split(' ')[1];
return await UserProfileService.instance.getUserProfileByToken(token);
}
async createWSSContext(opts: CreateWSSContextFnOptions): Promise<{ staff: UserProfile | undefined }> {
const token = opts.info.connectionParams?.token;
return await UserProfileService.instance.getUserProfileByToken(token);
}
2024-09-03 20:19:33 +08:00
trpc = initTRPC.context<Context>().create({
transformer: superjson,
2024-12-30 08:26:40 +08:00
errorFormatter: ({ error, shape }) => {
if (error.code !== 'UNAUTHORIZED') {
this.logger.error(error.message, error.stack);
}
return shape;
}
2024-07-11 11:00:51 +08:00
});
2024-12-30 08:26:40 +08:00
2024-07-11 11:00:51 +08:00
procedure = this.trpc.procedure;
router = this.trpc.router;
mergeRouters = this.trpc.mergeRouters;
2024-12-30 08:26:40 +08:00
2024-09-03 20:19:33 +08:00
// Define a protected procedure that ensures the user is authenticated
protectProcedure = this.procedure.use(async ({ ctx, next }) => {
2024-12-30 08:26:40 +08:00
if (!ctx?.staff) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: "未授权请求" });
2024-09-03 20:19:33 +08:00
}
return next({
ctx: {
// User value is confirmed to be non-null at this point
staff: ctx.staff,
},
});
2024-12-30 08:26:40 +08:00
2024-09-03 20:19:33 +08:00
});
2024-07-11 11:00:51 +08:00
}