/* * Copyright (C) Sapphirecode - All Rights Reserved * This file is part of Auth-Server-Helper which is released under MIT. * See file 'LICENSE' for full license details. * Created by Timo Hocker , August 2022 */ import IORedis from 'ioredis'; import { debug } from './debug'; import { LabelledKey } from './Key'; const logger = debug ('redis'); export type SyncClass = 'blacklist' | 'keystore' export type SyncValue = LabelledKey | string; export class Redis { private _redis: IORedis | null = null; public connect (url: string): void { const log = logger.extend ('connect'); log ('connecting to redis instance %s', url); if (this._redis !== null) { log ('disconnecting existing redis client'); this.disconnect (); } this._redis = new IORedis (url); this._redis.on ('connect', () => { log ('connected'); }); this._redis.on ('ready', () => { log ('ready'); }); this._redis.on ('error', (err) => { log ('error %o', err); }); this._redis.on ('reconnecting', () => { log ('reconnecting'); }); this._redis.on ('end', () => { log ('connection ended'); }); } public disconnect (): void { const log = logger.extend ('disconnect'); log ('disconnecting redis client'); if (this._redis === null) { log ('redis is inactive, skipping'); return; } this._redis.quit (); this._redis = null; log ('done'); } public async set ( sync_class: SyncClass, key: string, value: SyncValue ): Promise { const log = logger.extend ('set'); log ('trying to set %s value %s to redis', sync_class, key); if (this._redis === null) { log ('redis is inactive, skipping'); return; } let valid_for = null; if (sync_class === 'keystore') { valid_for = Math.floor ( (key.valid_until - (new Date) .getTime ()) / 1000 ); log ('key is valid for %d seconds', valid_for); } if (valid_for === null) await this._redis.set (key, JSON.stringify (value)); else await this._redis.setex (key, valid_for, JSON.stringify (value)); log ('saved value'); } public async get_key (index: string): Promise { const log = logger.extend ('get_key'); log ('trying to get key %s from redis', index); if (this._redis === null) { log ('redis is inactive, skipping'); return null; } const res = await this._redis.get (index); if (res === null) { log ('key not found in redis'); return null; } log ('key found'); return JSON.parse (res); } } export const redis = (new Redis);