Move redis code to middleware

This commit is contained in:
Ajay Ramachandran
2021-05-23 15:49:12 -04:00
parent 1b175d85c0
commit 799aef0b65
4 changed files with 50 additions and 37 deletions

View File

@@ -0,0 +1,35 @@
import redis from "../utils/redis";
import { Logger } from "../utils/logger";
import { skipSegmentsHashKey, skipSegmentsKey } from "./redisKeys";
import { Service, VideoID, VideoIDHash } from "../types/segments.model";
async function get<T>(fetchFromDB: () => Promise<T[]>, key: string): Promise<T[]> {
const {err, reply} = await redis.getAsync(key);
if (!err && reply) {
try {
Logger.debug("Got data from redis: " + reply);
return JSON.parse(reply);
} catch (e) {
// If all else, continue on to fetching from the database
}
}
const data = await fetchFromDB();
redis.setAsync(key, JSON.stringify(data));
return data;
}
function clearVideoCache(videoInfo: { videoID: VideoID; hashedVideoID: VideoIDHash; service: Service; }) {
if (videoInfo) {
redis.delAsync(skipSegmentsKey(videoInfo.videoID, videoInfo.service));
redis.delAsync(skipSegmentsHashKey(videoInfo.hashedVideoID, videoInfo.service));
}
}
export const QueryCacher = {
get,
clearVideoCache
}