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

61 lines
2.2 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';
import { env } from '@server/env';
2024-09-09 18:48:07 +08:00
import { db, Staff, JwtPayload } from "@nicestack/common"
2024-09-03 20:19:33 +08:00
import { JwtService } from '@nestjs/jwt';
2024-07-11 11:00:51 +08:00
2024-09-03 20:19:33 +08:00
type Context = Awaited<ReturnType<TrpcService['createContext']>>;
2024-07-11 11:00:51 +08:00
@Injectable()
export class TrpcService {
2024-09-10 11:23:02 +08:00
2024-09-03 20:19:33 +08:00
async createContext({
req,
res,
}: trpcExpress.CreateExpressContextOptions) {
const token = req.headers.authorization?.split(' ')[1];
2024-09-09 18:48:07 +08:00
let tokenData: JwtPayload | undefined = undefined;
2024-09-03 20:19:33 +08:00
let staff: Staff | undefined = undefined;
2024-09-10 11:23:02 +08:00
console.log(token)
2024-09-03 20:19:33 +08:00
if (token) {
try {
2024-09-10 11:23:02 +08:00
const jwtService = new JwtService()
tokenData = await jwtService.verifyAsync(token, { secret: env.JWT_SECRET }) as JwtPayload;
2024-09-03 20:19:33 +08:00
if (tokenData) {
// Fetch staff details from the database using tokenData.id
2024-09-09 18:48:07 +08:00
staff = await db.staff.findUnique({ where: { id: tokenData.sub } });
2024-09-03 20:19:33 +08:00
if (!staff) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: "User not found" });
}
}
} catch (error) {
// Enhanced error handling for invalid session data or token verification failure
throw new TRPCError({ code: 'INTERNAL_SERVER_ERROR', message: "Invalid session data or token" });
}
}
return {
2024-09-10 11:23:02 +08:00
staff
2024-09-03 20:19:33 +08:00
};
};
trpc = initTRPC.context<Context>().create({
transformer: superjson,
2024-07-11 11:00:51 +08:00
});
procedure = this.trpc.procedure;
router = this.trpc.router;
mergeRouters = this.trpc.mergeRouters;
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 }) => {
if (!ctx.staff) {
throw new TRPCError({ code: 'UNAUTHORIZED', message: "Unauthorized request" });
}
return next({
ctx: {
// User value is confirmed to be non-null at this point
staff: ctx.staff,
},
});
});
2024-07-11 11:00:51 +08:00
}