1
0
mirror of https://github.com/toast-ts/Daggerbot-TS.git synced 2024-11-17 20:30:58 -05:00
Daggerbot-TS/src/funcs/CacheServer.ts

50 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-10-02 18:40:03 -04:00
import {createClient, ErrorReply} from 'redis';
import Logger from '../helpers/Logger.js';
import TSClient from '../helpers/TSClient.js';
2023-10-02 18:40:03 -04:00
let Prefix = 'Cache';
const RedisClient = createClient({
url: (await TSClient.Token()).redis_uri,
2023-10-02 18:40:03 -04:00
database: 0,
name: 'Daggerbot',
socket: {
keepAlive: 15000,
timeout: 30000
}
});
export default class CacheServer {
protected static eventManager() {
RedisClient
.on('connect', ()=>Logger.forwardToConsole('log', Prefix, 'Connection to Redis has been established'))
2023-10-03 03:07:19 -04:00
.on('error', (err:ErrorReply)=>{
Logger.forwardToConsole('error', Prefix, `Encountered an error in Redis: ${err.message}`)
setTimeout(async()=>{
if (!RedisClient.isReady) {
Logger.forwardToConsole('log', Prefix, 'Client is zombified, starting a fresh connection...');
RedisClient.quit();
await RedisClient.connect();
}
}, 1500)
})
2023-10-02 18:40:03 -04:00
}
static async get(key:any) {
const cachedResult = await RedisClient.get(key);
2023-10-03 01:33:20 -04:00
if (cachedResult) return JSON.parse(cachedResult);
else return null
2023-10-02 18:40:03 -04:00
}
static async set(key:any, value:any) {
return await RedisClient.set(key, JSON.stringify(value));
}
static async expiry(key:any, time:number) {
2023-10-03 03:07:19 -04:00
return await RedisClient.expire(key, time); // NOTE: time is in seconds, not milliseconds -- you know what you did wrong
2023-10-02 18:40:03 -04:00
}
static async delete(key:any) {
return await RedisClient.del(key);
}
static init() {
2023-10-03 03:07:19 -04:00
RedisClient.connect();
2023-10-02 18:40:03 -04:00
this.eventManager();
}
}