doctor-mail/apps/server/src/trpc/trpc.service.ts

62 lines
2.0 KiB
TypeScript
Raw Normal View History

2025-01-22 18:56:27 +08:00
//trpc.service.ts
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';
2025-01-06 08:45:23 +08:00
import { db, JwtPayload, UserProfile, RolePerms } from '@nice/common';
2024-12-30 08:26:40 +08:00
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 {
2025-01-21 20:05:42 +08:00
private readonly logger = new Logger(TrpcService.name);
2024-09-10 11:23:02 +08:00
2025-01-21 20:05:42 +08:00
async createExpressContext(
opts: trpcExpress.CreateExpressContextOptions,
2025-01-22 18:56:27 +08:00
): Promise<{
staff: UserProfile | undefined;
req: trpcExpress.CreateExpressContextOptions['req'];
}> {
2025-01-21 20:05:42 +08:00
const token = opts.req.headers.authorization?.split(' ')[1];
2025-01-22 18:56:27 +08:00
const staff =
await UserProfileService.instance.getUserProfileByToken(token);
return {
staff: staff.staff,
req: opts.req,
};
2025-01-21 20:05:42 +08:00
}
async createWSSContext(
opts: CreateWSSContextFnOptions,
): Promise<{ staff: UserProfile | undefined }> {
const token = opts.info.connectionParams?.token;
return await UserProfileService.instance.getUserProfileByToken(token);
}
trpc = initTRPC.context<Context>().create({
transformer: superjson,
errorFormatter: ({ error, shape }) => {
if (error.code !== 'UNAUTHORIZED') {
this.logger.error(error.message, error.stack);
}
return shape;
},
});
2024-12-30 08:26:40 +08:00
2025-01-21 20:05:42 +08:00
procedure = this.trpc.procedure;
router = this.trpc.router;
mergeRouters = this.trpc.mergeRouters;
2024-12-30 08:26:40 +08:00
2025-01-21 20:05:42 +08:00
// Define a protected procedure that ensures the user is authenticated
protectProcedure = this.procedure.use(async ({ ctx, next }) => {
2025-01-24 00:19:02 +08:00
// if (!ctx?.staff) {
// throw new TRPCError({ code: 'UNAUTHORIZED', message: '未授权请求' });
// }
2025-01-21 20:05:42 +08:00
return next({
ctx: {
// User value is confirmed to be non-null at this point
staff: ctx.staff,
2025-01-22 18:56:27 +08:00
req: ctx.req,
2025-01-21 20:05:42 +08:00
},
2024-09-03 20:19:33 +08:00
});
2025-01-21 20:05:42 +08:00
});
2024-07-11 11:00:51 +08:00
}