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

Dedupe the get and set functions.

This commit is contained in:
AnxietyisReal 2023-12-27 09:46:08 +11:00
parent b7cad061bd
commit c80a7e9d15
5 changed files with 25 additions and 28 deletions

View File

@ -2,7 +2,6 @@ import {createClient, ErrorReply} from 'redis';
import Logger from '../helpers/Logger.js'; import Logger from '../helpers/Logger.js';
import TSClient from '../helpers/TSClient.js'; import TSClient from '../helpers/TSClient.js';
let Prefix = 'Cache';
const RedisClient = createClient({ const RedisClient = createClient({
url: (await TSClient()).redis_uri, url: (await TSClient()).redis_uri,
database: 0, database: 0,
@ -11,35 +10,32 @@ const RedisClient = createClient({
}); });
export default class CacheServer { export default class CacheServer {
protected static prefix = 'Cache';
protected static eventManager() { protected static eventManager() {
RedisClient RedisClient
.on('connect', ()=>Logger.console('log', Prefix, 'Connection to Redis has been established')) .on('connect', ()=>Logger.console('log', this.prefix, 'Connection to Redis has been established'))
.on('error', (err:ErrorReply)=>{ .on('error', (err:ErrorReply)=>{
Logger.console('error', Prefix, `Encountered an error in Redis: ${err.message}`) Logger.console('error', this.prefix, `Encountered an error in Redis: ${err.message}`)
setTimeout(async()=>{ setTimeout(async()=>{
if (!RedisClient.isReady) { if (!RedisClient.isReady) {
Logger.console('log', Prefix, 'Client is zombified, starting a fresh connection...'); Logger.console('log', this.prefix, 'Client is zombified, starting a fresh connection...');
RedisClient.quit(); RedisClient.quit();
await RedisClient.connect(); await RedisClient.connect();
} }
}, 1500) }, 1500)
}) })
} }
public static async get(key:any) { public static async get(key:any, jsonMode:boolean):Promise<any> {
const cachedResult = await RedisClient.get(key); let cachedResult:any;
if (cachedResult) return JSON.parse(cachedResult); if (jsonMode) cachedResult = await RedisClient.json.get(key);
else return null else {
cachedResult = await RedisClient.get(key);
if (cachedResult) cachedResult = JSON.parse(cachedResult);
} }
public static async set(key:any, value:any) {
return await RedisClient.set(key, JSON.stringify(value));
} }
public static async getJSON(key:any) { public static async set(key:any, value:any, jsonMode:boolean):Promise<any> {
const cachedResult = await RedisClient.json.get(key); if (jsonMode) return await RedisClient.json.set(key, '.', value);
if (cachedResult) return cachedResult; else return await RedisClient.set(key, JSON.stringify(value));
else return null
}
public static async setJSON(key:any, value:any) {
return await RedisClient.json.set(key, '.', value);
} }
public static async expiry(key:any, time:number) { 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 return await RedisClient.expire(key, time); // NOTE: time is in seconds, not milliseconds -- you know what you did wrong
@ -52,7 +48,8 @@ export default class CacheServer {
RedisClient.connect(); RedisClient.connect();
this.eventManager(); this.eventManager();
} catch { } catch {
console.error('Cannot initialize RedisClient -- is Redis running?') console.error('Cannot initialize RedisClient -- is Redis running?');
process.exit(1);
} }
} }
} }

View File

@ -109,12 +109,12 @@ export class MPServerSvc {
} else return false; } else return false;
} }
async findInCache(): Promise<IServer[]> { async findInCache(): Promise<IServer[]> {
const cachedResult = await CacheServer.getJSON(cacheKey); const cachedResult = await CacheServer.get(cacheKey, true);
let result; let result;
if (cachedResult) result = cachedResult; if (cachedResult) result = cachedResult;
else { else {
result = await this.model.findAll(); result = await this.model.findAll();
CacheServer.setJSON(cacheKey, result).then(()=>CacheServer.expiry(cacheKey, 1800)); CacheServer.set(cacheKey, result, true).then(()=>CacheServer.expiry(cacheKey, 1800));
} }
return result; return result;
} }

View File

@ -124,12 +124,12 @@ export class PunishmentsSvc {
} }
async findInCache():Promise<any> { async findInCache():Promise<any> {
const cacheKey = 'punishments'; const cacheKey = 'punishments';
const cachedResult = await CacheServer.getJSON(cacheKey); const cachedResult = await CacheServer.get(cacheKey, true);
let result; let result;
if (cachedResult) result = cachedResult; if (cachedResult) result = cachedResult;
else { else {
result = await this.model.findAll(); result = await this.model.findAll();
CacheServer.setJSON(cacheKey, result).then(()=>CacheServer.expiry(cacheKey, 20)); CacheServer.set(cacheKey, result, true).then(()=>CacheServer.expiry(cacheKey, 20));
} }
return result; return result;
} }

View File

@ -88,12 +88,12 @@ export class TagSystemSvc {
} }
async findInCache(): Promise<Tags[]> { async findInCache(): Promise<Tags[]> {
const cacheKey = 'tags'; const cacheKey = 'tags';
const cachedResult = await CacheServer.getJSON(cacheKey); const cachedResult = await CacheServer.get(cacheKey, true);
let result; let result;
if (cachedResult) result = cachedResult; if (cachedResult) result = cachedResult;
else { else {
result = await this.model.findAll(); result = await this.model.findAll();
CacheServer.setJSON(cacheKey, result).then(()=>CacheServer.expiry(cacheKey, 240)); CacheServer.set(cacheKey, result, true).then(()=>CacheServer.expiry(cacheKey, 240));
} }
return result; return result;
} }

View File

@ -35,13 +35,13 @@ export default async(client:TClient)=>{
const getVideoId = (index:number)=>Data.items[index].snippet.thumbnails.default.url.split('/')[4]; const getVideoId = (index:number)=>Data.items[index].snippet.thumbnails.default.url.split('/')[4];
const videoUrl = `https://www.youtube.com/watch?v=${getVideoId(0)}`; const videoUrl = `https://www.youtube.com/watch?v=${getVideoId(0)}`;
const cacheKey = `YTCache:${YTChannelID}`; const cacheKey = `YTCache:${YTChannelID}`;
const cachedVideoId = await CacheServer.get(cacheKey); const cachedVideoId = await CacheServer.get(cacheKey, false);
if (!cachedVideoId) { if (!cachedVideoId) {
await CacheServer.set(cacheKey, getVideoId(0)).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry)); await CacheServer.set(cacheKey, getVideoId(0), false).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry));
return; return;
} }
if (getVideoId(1) === cachedVideoId) { if (getVideoId(1) === cachedVideoId) {
await CacheServer.delete(cacheKey).then(async()=>await CacheServer.set(cacheKey, getVideoId(0)).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry))); await CacheServer.delete(cacheKey).then(async()=>await CacheServer.set(cacheKey, getVideoId(0), false).then(async()=>await CacheServer.expiry(cacheKey, cacheExpiry)));
(client.channels.resolve(DiscordChannelID) as TextChannel).send({ (client.channels.resolve(DiscordChannelID) as TextChannel).send({
content: `${MessageTool.formatMention(DiscordRoleID, 'role')}\n**${YTChannelName}** just uploaded a video!\n${videoUrl}`, allowedMentions: {parse: ['roles']}, content: `${MessageTool.formatMention(DiscordRoleID, 'role')}\n**${YTChannelName}** just uploaded a video!\n${videoUrl}`, allowedMentions: {parse: ['roles']},