Initial commit of redis session for crosstalk

master
j 2024-03-23 01:01:18 -04:00
parent 87ff7c7208
commit 96e3661fe2
1 changed files with 87 additions and 0 deletions

View File

@ -0,0 +1,87 @@
import Redis, { RedisOptions } from 'ioredis';
import dotenv from 'dotenv';
dotenv.config();
interface RedisConfig extends RedisOptions {
host: string;
port: number;
password?: string;
}
class RedisSessionManager {
private static instance: RedisSessionManager;
public readonly client: Redis;
private subscriber: Redis | null = null;
private constructor() {
const redisConfig: RedisConfig = {
host: process.env.REDIS_HOST!,
port: Number(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD || undefined,
showFriendlyErrorStack: true,
};
this.client = new Redis(redisConfig);
}
public static getInstance(): RedisSessionManager {
if (!RedisSessionManager.instance) {
RedisSessionManager.instance = new RedisSessionManager();
}
return RedisSessionManager.instance;
}
async subscribe(channel: string, messageHandler: (channel: string, message: string) => void): Promise<void> {
if (!this.subscriber) {
this.subscriber = new Redis({
host: process.env.REDIS_HOST!,
port: Number(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD || undefined,
showFriendlyErrorStack: true,
});
}
await this.subscriber.subscribe(channel, (err, count) => {
if (err) {
console.error(`Failed to subscribe: ${err.message}`);
return;
}
console.log(`Subscribed to ${count} channel(s). Currently subscribed to ${channel}`);
});
this.subscriber.on('message', messageHandler);
}
async unsubscribe(channel: string): Promise<void> {
if (this.subscriber) {
await this.subscriber.unsubscribe(channel);
console.log(`Unsubscribed from ${channel}`);
}
}
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> {
if (this.subscriber) {
await this.subscriber.quit();
}
await this.client.quit();
}
}
export default RedisSessionManager;