umami/lib/redis.js

80 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-08-29 19:47:01 +02:00
import Redis from 'ioredis';
2022-08-27 05:21:53 +02:00
import { startOfMonth } from 'date-fns';
2022-08-29 19:47:31 +02:00
import debug from 'debug';
2022-08-29 05:20:54 +02:00
import { getSessions, getAllWebsites } from 'queries';
import { REDIS } from 'lib/db';
2022-08-28 06:38:35 +02:00
2022-08-29 19:47:31 +02:00
const log = debug('umami:redis');
2022-08-29 05:20:54 +02:00
const INITIALIZED = 'redis:initialized';
2022-08-29 22:04:58 +02:00
export const DELETED = 'deleted';
2022-08-27 05:21:53 +02:00
2022-10-07 00:00:16 +02:00
let redis;
const enabled = Boolean(process.env.REDIS_URL);
2022-08-29 19:47:01 +02:00
function getClient() {
if (!process.env.REDIS_URL) {
return null;
}
const redis = new Redis(process.env.REDIS_URL, {
retryStrategy(times) {
log(`Redis reconnecting attempt: ${times}`);
return 5000;
},
});
2022-08-27 05:21:53 +02:00
if (process.env.NODE_ENV !== 'production') {
2022-08-28 06:38:35 +02:00
global[REDIS] = redis;
2022-08-27 05:21:53 +02:00
}
log('Redis initialized');
2022-08-28 06:38:35 +02:00
return redis;
}
2022-08-27 05:21:53 +02:00
async function stageData() {
2022-08-29 19:47:01 +02:00
const sessions = await getSessions([], startOfMonth(new Date()));
2022-08-27 05:21:53 +02:00
const websites = await getAllWebsites();
const sessionUuids = sessions.map(a => {
return { key: `session:${a.sessionUuid}`, value: 1 };
2022-08-27 05:21:53 +02:00
});
const websiteIds = websites.map(a => {
return { key: `website:${a.websiteUuid}`, value: Number(a.websiteId) };
2022-08-27 05:21:53 +02:00
});
2022-10-07 00:00:16 +02:00
await addSet(sessionUuids);
await addSet(websiteIds);
2022-08-27 05:21:53 +02:00
2022-08-29 05:20:54 +02:00
await redis.set(INITIALIZED, 1);
2022-08-27 05:21:53 +02:00
}
2022-10-07 00:00:16 +02:00
async function addSet(ids) {
2022-08-27 05:21:53 +02:00
for (let i = 0; i < ids.length; i++) {
const { key, value } = ids[i];
await redis.set(key, value);
}
}
2022-08-28 06:38:35 +02:00
2022-10-07 00:00:16 +02:00
async function get(key) {
await connect();
return redis.get(key);
}
async function set(key, value) {
await connect();
return redis.set(key, value);
}
async function connect() {
if (!redis) {
2022-10-07 01:41:37 +02:00
redis = process.env.REDIS_URL && (global[REDIS] || getClient());
2022-08-28 06:38:35 +02:00
}
2022-10-07 00:00:16 +02:00
return redis;
}
export default { enabled, client: redis, log, connect, get, set, stageData };