implement redis cache for context
This commit is contained in:
15
src/Redis/redis.module.ts
Normal file
15
src/Redis/redis.module.ts
Normal 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 {}
|
||||
41
src/Redis/redis.service.ts
Normal file
41
src/Redis/redis.service.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user