implement redis cache for context
This commit is contained in:
@@ -1,12 +1,22 @@
|
||||
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
|
||||
import {
|
||||
Inject,
|
||||
Injectable,
|
||||
Logger,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { PrismaService } from '../Prisma/prisma.service';
|
||||
import { Request } from 'express';
|
||||
import { clerkClient } from '@clerk/express';
|
||||
|
||||
import { RedisService } from '../Redis/redis.service';
|
||||
|
||||
@Injectable()
|
||||
export class GraphqlService {
|
||||
constructor(private readonly prisma: PrismaService) {}
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
@Inject('REDIS_CLIENT') private readonly redis: RedisService,
|
||||
) {}
|
||||
|
||||
async acquireContext(req: Request) {
|
||||
// get x-session-id from headers
|
||||
@@ -24,6 +34,11 @@ export class GraphqlService {
|
||||
if (disableAuth) {
|
||||
return null;
|
||||
}
|
||||
// redis context cache
|
||||
const cachedUser = await this.redis.getUser(sessionId);
|
||||
if (cachedUser) {
|
||||
return cachedUser;
|
||||
}
|
||||
// check if the token is valid
|
||||
const session = await clerkClient.sessions.getSession(sessionId as string);
|
||||
if (!session) {
|
||||
@@ -35,7 +50,7 @@ export class GraphqlService {
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('User not found');
|
||||
}
|
||||
Logger.log(`User ${user.name} with id ${user.id} acquired context`);
|
||||
await this.redis.setUser(sessionId, user, session.expireAt);
|
||||
return user;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user