initial commit of redis session and comment service
parent
c152333303
commit
27582f9242
|
@ -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
|
|
@ -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;
|
Loading…
Reference in New Issue