optimize context

This commit is contained in:
2024-10-29 01:54:19 +07:00
parent 34cea2ccd3
commit ba54d3466c
7 changed files with 11 additions and 77 deletions

View File

@@ -39,6 +39,7 @@ services:
- OPENAI_BASE_URL=https://api.gpt.ge/v1
- OPENAI_MAX_RETRIES=10
- PRISMA_MAX_RETRY=10
- REDIS_URL=redis://10.0.27.1:6379
labels:
- 'traefik.enable=true'
- 'traefik.http.routers.api.rule=Host(`api.epess.org`)'

View File

@@ -1,4 +1,4 @@
import { Global, MiddlewareConsumer, Module } from '@nestjs/common';
import { Global, Module } from '@nestjs/common';
import { AdminNoteModule } from '../AdminNote/adminnote.module';
import { ApolloDriverConfig } from '@nestjs/apollo';
@@ -9,8 +9,8 @@ import { CenterMentorModule } from '../CenterMentor/centermentor.module';
import { CenterModule } from '../Center/center.module';
import { ChatroomModule } from '../ChatRoom/chatroom.module';
import { CommonModule } from '../common/common.module';
import { ConfigModule } from '@nestjs/config';
import { GraphQLModule } from '@nestjs/graphql';
import { GraphQLValidationMiddleware } from '../middlewares/graphql.middleware';
import { GraphqlService } from './graphql.service';
import { ManagedServiceModule } from '../ManagedService/managedservice.module';
import { MessageModule } from '../Message/message.module';
@@ -43,6 +43,9 @@ import { initContextCache } from '@pothos/core';
@Global()
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
CommonModule,
PrismaModule,
RedisModule,
@@ -96,6 +99,7 @@ import { initContextCache } from '@pothos/core';
}),
],
providers: [
RedisService,
{
provide: GraphqlService,
useFactory: (prisma: PrismaService, redis: RedisService) =>
@@ -113,12 +117,6 @@ import { initContextCache } from '@pothos/core';
inject: [Builder],
},
],
exports: [Builder, PrismaCrudGenerator, GraphqlService],
exports: [Builder, PrismaCrudGenerator, GraphqlService, RedisService],
})
export class GraphqlModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(GraphQLValidationMiddleware) // Apply the custom middleware
.forRoutes(process.env.API_PATH + '/graphql'); // Ensure it only applies to the /graphql endpoint
}
}
export class GraphqlModule {}

View File

@@ -130,23 +130,7 @@ export class UserSchema extends PothosSchema {
description: 'Retrieve the current user by token.',
type: this.user(),
resolve: async (query, root, args, ctx) => {
// get session id from X-Session-Id
const sessionId = ctx.req.headers['x-session-id'];
if (!sessionId)
throw new UnauthorizedException({
message: 'No session ID found',
});
// verify the token
const session = await clerkClient.sessions.getSession(
sessionId as string,
);
if (!session) throw new UnauthorizedException();
const user = await this.prisma.user.findUnique({
where: { id: session.userId },
});
if (!user) throw new UnauthorizedException();
ctx.me = user;
return user;
return ctx.me;
},
}),

View File

@@ -4,6 +4,7 @@ import { GraphqlModule } from './Graphql/graphql.module';
import { MailModule } from './Mail/mail.module';
import { Module } from '@nestjs/common';
import { RestfulModule } from './Restful/restful.module';
@Module({
imports: [
ConfigModule.forRoot({

View File

@@ -1,37 +0,0 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
@Injectable()
export class GraphQLValidationMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
// handle post request
if (
req.method === 'POST' &&
req.headers['content-type'] === 'application/json'
) {
const { query, mutation, subscription } = req.body;
// If none of these are present, return a custom error response
if (
!query &&
!mutation &&
!subscription &&
query.trim() === '' &&
mutation.trim() === '' &&
subscription.trim() === ''
) {
return res.status(400).json({
errors: [
{
message:
'Must provide a valid GraphQL query, mutation, or subscription.',
},
],
});
}
}
// Continue to the next middleware or GraphQL handler
next();
}
}

View File

@@ -1,13 +0,0 @@
import { Injectable, NestMiddleware } from '@nestjs/common';
import { PrismaService } from '../Prisma/prisma.service';
@Injectable()
export class PrismaContextMiddleware implements NestMiddleware {
constructor(private readonly prisma: PrismaService) {}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
use(req: any, res: any, next: () => void) {
req.prisma = this.prisma; // Attach Prisma client to request object
next();
}
}