Database refactoring.

This commit is contained in:
Mike Cao 2022-08-27 21:38:35 -07:00
parent bb184dc2cc
commit 467c7f289f
37 changed files with 566 additions and 591 deletions

View file

@ -1,6 +1,10 @@
import { createClient } from 'redis';
import { startOfMonth } from 'date-fns';
import { getSessions, getAllWebsites } from '/queries';
import debug from 'debug';
const log = debug('db:redis');
const REDIS = Symbol.for('redis');
async function getClient() {
const redis = new createClient({
@ -10,30 +14,16 @@ async function getClient() {
await redis.connect();
if (process.env.LOG_QUERY) {
redis.on('error', err => console.log('Redis Client Error', err));
redis.on('error', err => log(err));
}
if (process.env.NODE_ENV !== 'production') {
global[REDIS] = redis;
}
return redis;
}
let redis = null;
(async () => {
redis = global.redis || (await getClient());
if (process.env.NODE_ENV !== 'production') {
global.redis = redis;
}
const value = await redis.get('initialized');
if (!value) {
await stageData();
}
})();
export default redis;
async function stageData() {
const sessions = await getSessions([], startOfMonth(new Date()).toUTCString());
const websites = await getAllWebsites();
@ -57,3 +47,18 @@ async function addRedis(ids) {
await redis.set(key, value);
}
}
// Initialization
let redis = null;
(async () => {
redis = global[REDIS] || (await getClient());
const value = await redis.get('initialized');
if (!value) {
await stageData();
}
})();
export default redis;