initial commit of redis session and comment service

master
j 2024-03-22 01:27:58 -04:00
parent c152333303
commit 27582f9242
2 changed files with 72 additions and 0 deletions

View File

@ -0,0 +1,24 @@
import { Comment } from "../../rdrama/models/Comment";
import RedisSessionManager from "../session/SessionManager";
class RedisCommentService {
static async storeComment(comment: Comment): Promise<void> {
const redisManager = RedisSessionManager.getInstance();
await redisManager.storeObject('comment', comment.id.toString(), comment);
}
static async retrieveComment(commentId: string): Promise<Comment | null> {
const redisManager = RedisSessionManager.getInstance();
const result = await redisManager.retrieveObject('comment', commentId);
if (result) return result as Comment;
return null;
}
static async publishComment(comment: Comment): Promise<number> {
const redisManager = RedisSessionManager.getInstance();
return redisManager.publishObject('newCommentsChannel', comment);
}
}
export default RedisCommentService

View File

@ -0,0 +1,48 @@
import Redis from 'ioredis';
import dotenv from 'dotenv';
dotenv.config();
class RedisSessionManager {
private static instance: RedisSessionManager;
public readonly client: Redis;
private constructor() {
this.client = new Redis({
host: process.env.REDIS_HOST,
port: Number(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD || undefined,
showFriendlyErrorStack: true,
});
}
public static getInstance(): RedisSessionManager {
if (!RedisSessionManager.instance) {
RedisSessionManager.instance = new RedisSessionManager();
}
return RedisSessionManager.instance;
}
async storeObject(keyPrefix: string, objectId: string, data: Record<string, any>, expirationSec: number = 3600): Promise<void> {
const key = `${keyPrefix}:${objectId}`;
const dataToStore = JSON.stringify(data);
await this.client.set(key, dataToStore, 'EX', expirationSec);
}
async retrieveObject(keyPrefix: string, objectId: string): Promise<Record<string, any> | null> {
const key = `${keyPrefix}:${objectId}`;
const data = await this.client.get(key);
return data ? JSON.parse(data) : null;
}
async publishObject(channel: string, data: Record<string, any>): Promise<number> {
const dataToPublish = JSON.stringify(data);
return this.client.publish(channel, dataToPublish);
}
async shutdown(): Promise<void> {
await this.client.quit();
}
}
export default RedisSessionManager;