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-08-29 19:47:01 +02:00
|
|
|
function getClient() {
|
2022-09-01 20:11:11 +02:00
|
|
|
if (!process.env.REDIS_URL) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-08-29 19:47:01 +02:00
|
|
|
const redis = new Redis(process.env.REDIS_URL);
|
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
|
|
|
}
|
|
|
|
|
2022-09-05 20:36:57 +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 => {
|
2022-08-29 19:47:01 +02:00
|
|
|
return { key: `session:${a.session_uuid}`, value: 1 };
|
2022-08-27 05:21:53 +02:00
|
|
|
});
|
|
|
|
const websiteIds = websites.map(a => {
|
|
|
|
return { key: `website:${a.website_uuid}`, value: Number(a.website_id) };
|
|
|
|
});
|
|
|
|
|
|
|
|
await addRedis(sessionUuids);
|
|
|
|
await addRedis(websiteIds);
|
|
|
|
|
2022-08-29 05:20:54 +02:00
|
|
|
await redis.set(INITIALIZED, 1);
|
2022-08-27 05:21:53 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function addRedis(ids) {
|
|
|
|
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
|
|
|
|
|
|
|
// Initialization
|
2022-08-29 19:47:01 +02:00
|
|
|
const redis = process.env.REDIS_URL && (global[REDIS] || getClient());
|
2022-08-28 06:38:35 +02:00
|
|
|
|
|
|
|
(async () => {
|
2022-08-30 09:03:22 +02:00
|
|
|
if (redis && !(await redis.get(INITIALIZED))) {
|
2022-08-29 19:47:01 +02:00
|
|
|
await stageData();
|
2022-08-28 06:38:35 +02:00
|
|
|
}
|
|
|
|
})();
|
|
|
|
|
2022-08-29 19:47:31 +02:00
|
|
|
export default { client: redis, stageData, log };
|