implement redis cache for context

This commit is contained in:
2024-10-29 00:56:23 +07:00
parent ae1aa64b41
commit 34cea2ccd3
18 changed files with 477 additions and 55 deletions

15
src/Redis/redis.module.ts Normal file
View File

@@ -0,0 +1,15 @@
import { Global, Module } from '@nestjs/common';
import { RedisService } from './redis.service';
@Global()
@Module({
providers: [
{
provide: 'REDIS_CLIENT',
useClass: RedisService,
},
],
exports: ['REDIS_CLIENT'],
})
export class RedisModule {}

View File

@@ -0,0 +1,41 @@
import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';
import { User } from '@prisma/client';
@Injectable()
export class RedisService {
private readonly redis: Redis;
constructor() {
this.redis = new Redis(process.env.REDIS_URL as string);
}
async get(key: string) {
return await this.redis.get(key);
}
async set(key: string, value: string, expireAt: number) {
return await this.redis.set(key, value, 'EXAT', expireAt);
}
async del(key: string) {
return await this.redis.del(key);
}
async close() {
return await this.redis.quit();
}
async getUser(sessionId: string) {
const userData = await this.get(sessionId);
if (!userData) {
return null;
}
const retrievedUser: User = JSON.parse(userData);
return retrievedUser;
}
async setUser(sessionId: string, user: User, expireAt: number) {
return await this.set(sessionId, JSON.stringify(user), expireAt);
}
}