2023-12-24 10:21:40 -05:00
|
|
|
import {createClient, ErrorReply} from 'redis';
|
|
|
|
import Logger from '../helpers/Logger.js';
|
|
|
|
import TSClient from '../helpers/TSClient.js';
|
|
|
|
|
|
|
|
const RedisClient = createClient({
|
|
|
|
url: (await TSClient()).redis_uri,
|
|
|
|
database: 0,
|
|
|
|
name: 'Daggerbot',
|
|
|
|
socket: { keepAlive: 15000, timeout: 30000 }
|
|
|
|
});
|
|
|
|
|
|
|
|
export default class CacheServer {
|
2023-12-26 17:46:08 -05:00
|
|
|
protected static prefix = 'Cache';
|
2023-12-24 10:21:40 -05:00
|
|
|
protected static eventManager() {
|
|
|
|
RedisClient
|
2023-12-26 17:46:08 -05:00
|
|
|
.on('connect', ()=>Logger.console('log', this.prefix, 'Connection to Redis has been established'))
|
2023-12-24 10:21:40 -05:00
|
|
|
.on('error', (err:ErrorReply)=>{
|
2023-12-26 17:46:08 -05:00
|
|
|
Logger.console('error', this.prefix, `Encountered an error in Redis: ${err.message}`)
|
2023-12-24 10:21:40 -05:00
|
|
|
setTimeout(async()=>{
|
|
|
|
if (!RedisClient.isReady) {
|
2023-12-26 17:46:08 -05:00
|
|
|
Logger.console('log', this.prefix, 'Client is zombified, starting a fresh connection...');
|
2023-12-24 10:21:40 -05:00
|
|
|
RedisClient.quit();
|
|
|
|
await RedisClient.connect();
|
|
|
|
}
|
|
|
|
}, 1500)
|
|
|
|
})
|
|
|
|
}
|
2023-12-26 17:46:08 -05:00
|
|
|
public static async get(key:any, jsonMode:boolean):Promise<any> {
|
|
|
|
let cachedResult:any;
|
|
|
|
if (jsonMode) cachedResult = await RedisClient.json.get(key);
|
|
|
|
else {
|
|
|
|
cachedResult = await RedisClient.get(key);
|
|
|
|
if (cachedResult) cachedResult = JSON.parse(cachedResult);
|
|
|
|
}
|
2023-12-29 01:23:04 -05:00
|
|
|
return cachedResult;
|
2023-12-24 10:21:40 -05:00
|
|
|
}
|
2023-12-26 17:46:08 -05:00
|
|
|
public static async set(key:any, value:any, jsonMode:boolean):Promise<any> {
|
|
|
|
if (jsonMode) return await RedisClient.json.set(key, '.', value);
|
|
|
|
else return await RedisClient.set(key, JSON.stringify(value));
|
2023-12-24 10:21:40 -05:00
|
|
|
}
|
|
|
|
public static async expiry(key:any, time:number) {
|
|
|
|
return await RedisClient.expire(key, time); // NOTE: time is in seconds, not milliseconds -- you know what you did wrong
|
|
|
|
}
|
|
|
|
public static async delete(key:any) {
|
|
|
|
return await RedisClient.del(key);
|
|
|
|
}
|
|
|
|
public static init() {
|
|
|
|
try {
|
|
|
|
RedisClient.connect();
|
|
|
|
this.eventManager();
|
|
|
|
} catch {
|
2023-12-26 17:46:08 -05:00
|
|
|
console.error('Cannot initialize RedisClient -- is Redis running?');
|
|
|
|
process.exit(1);
|
2023-12-24 10:21:40 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|