refactor source code
This commit is contained in:
@@ -3,13 +3,13 @@ import {
|
||||
Injectable,
|
||||
Logger,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
} from '@nestjs/common'
|
||||
|
||||
import { PrismaService } from '../Prisma/prisma.service';
|
||||
import { Request } from 'express';
|
||||
import { clerkClient } from '@clerk/express';
|
||||
import { PrismaService } from '../Prisma/prisma.service'
|
||||
import { Request } from 'express'
|
||||
import { clerkClient } from '@clerk/express'
|
||||
|
||||
import { RedisService } from '../Redis/redis.service';
|
||||
import { RedisService } from '../Redis/redis.service'
|
||||
|
||||
@Injectable()
|
||||
export class GraphqlService {
|
||||
@@ -20,37 +20,37 @@ export class GraphqlService {
|
||||
|
||||
async acquireContext(req: Request) {
|
||||
// get x-session-id from headers
|
||||
let sessionId: string;
|
||||
const disableAuth = process.env.DISABLE_AUTH === 'true';
|
||||
let sessionId: string
|
||||
const disableAuth = process.env.DISABLE_AUTH === 'true'
|
||||
try {
|
||||
sessionId = req.headers['x-session-id'] as string;
|
||||
sessionId = req.headers['x-session-id'] as string
|
||||
} catch (error) {
|
||||
Logger.error('Error acquiring context', error);
|
||||
Logger.error('Error acquiring context', error)
|
||||
if (disableAuth) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
throw new UnauthorizedException('Must provide a session ID');
|
||||
throw new UnauthorizedException('Must provide a session ID')
|
||||
}
|
||||
if (disableAuth) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
// redis context cache
|
||||
const cachedUser = await this.redis.getUser(sessionId);
|
||||
const cachedUser = await this.redis.getUser(sessionId)
|
||||
if (cachedUser) {
|
||||
return cachedUser;
|
||||
return cachedUser
|
||||
}
|
||||
// check if the token is valid
|
||||
const session = await clerkClient.sessions.getSession(sessionId as string);
|
||||
const session = await clerkClient.sessions.getSession(sessionId as string)
|
||||
if (!session) {
|
||||
throw new UnauthorizedException('Invalid session');
|
||||
throw new UnauthorizedException('Invalid session')
|
||||
}
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: session.userId },
|
||||
});
|
||||
})
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User not found');
|
||||
throw new UnauthorizedException('User not found')
|
||||
}
|
||||
await this.redis.setUser(sessionId, user, session.expireAt);
|
||||
return user;
|
||||
await this.redis.setUser(sessionId, user, session.expireAt)
|
||||
return user
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user