Add connect methods to libraries.

This commit is contained in:
Mike Cao 2022-10-06 15:00:16 -07:00
parent 186f484ff1
commit e442617421
5 changed files with 59 additions and 28 deletions

View file

@ -8,6 +8,9 @@ const log = debug('umami:redis');
const INITIALIZED = 'redis:initialized';
export const DELETED = 'deleted';
let redis;
const enabled = Boolean(process.env.REDIS_URL);
function getClient() {
if (!process.env.REDIS_URL) {
return null;
@ -40,26 +43,41 @@ async function stageData() {
return { key: `website:${a.website_uuid}`, value: Number(a.website_id) };
});
await addRedis(sessionUuids);
await addRedis(websiteIds);
await addSet(sessionUuids);
await addSet(websiteIds);
await redis.set(INITIALIZED, 1);
}
async function addRedis(ids) {
async function addSet(ids) {
for (let i = 0; i < ids.length; i++) {
const { key, value } = ids[i];
await redis.set(key, value);
}
}
// Initialization
const redis = process.env.REDIS_URL && (global[REDIS] || getClient());
async function get(key) {
await connect();
(async () => {
if (redis && !(await redis.get(INITIALIZED))) {
await stageData();
return redis.get(key);
}
async function set(key, value) {
await connect();
return redis.set(key, value);
}
async function connect() {
if (!redis) {
process.env.REDIS_URL && (global[REDIS] || getClient());
if (!(await redis.get(INITIALIZED))) {
await stageData();
}
}
})();
export default { client: redis, stageData, log };
return redis;
}
export default { enabled, client: redis, log, connect, get, set, stageData };