import {createClient, RedisClientType} from 'redis'; import Config from "../config"; import {UserSession} from "../typesRelated/types"; class RedisUtils { private readonly client: RedisClientType; private readonly podIdToChatIdKey: string; constructor() { this.client = createClient({ socket: { host: Config.redisHost, port: Config.redisPort }, password: Config.redisPassword }); this.client.connect().catch(console.error); this.podIdToChatIdKey = 'pod_id_to_chat_id'; } async init() { await this.defineVariables(); } async setValue(key: string, value: any) { if (['string', 'number'].includes(typeof value)) { await this.client.set(key, value); } else { await this.client.set(key, JSON.stringify(value)); } } async getValue(key: string): Promise { const value = await this.client.get(key); if (typeof value === 'object') { return value; } try { return JSON.parse(value); } catch (e) { return value; } } async deleteValue(key: string) { return this.client.del(key); } async defineVariables() { // const pIdToCId = this.getValue(this.podIdToChatIdKey); // if (!pIdToCId || typeof pIdToCId !== 'object') { // await this.setValue(this.podIdToChatIdKey, {}); // } } // podIdToChatId(podId: string) { // const pIdToCId = this.getValue(this.podIdToChatIdKey); // return pIdToCId[podId]; // } saveSession(userId: number, session: UserSession) { return this.setValue(`user:${userId}`, session); } getSession(userId: number): Promise { return this.getValue(`user:${userId}`); } deleteSession(userId: number) { return this.deleteValue(`user:${userId}`); } } export default new RedisUtils();