umami/lib/redis.js

65 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-11-22 07:32:55 +01:00
import { createClient } from 'redis';
2022-08-29 19:47:31 +02:00
import debug from 'debug';
2022-08-28 06:38:35 +02:00
2022-08-29 19:47:31 +02:00
const log = debug('umami:redis');
2022-11-22 07:32:55 +01:00
const REDIS = Symbol();
const DELETED = 'DELETED';
2022-08-27 05:21:53 +02:00
2022-10-07 00:00:16 +02:00
let redis;
const url = process.env.REDIS_URL;
const enabled = Boolean(url);
2022-10-07 00:00:16 +02:00
2022-11-22 07:32:55 +01:00
async function getClient() {
if (!enabled) {
return null;
}
const client = createClient({ url });
2022-11-22 07:32:55 +01:00
client.on('error', err => log(err));
await client.connect();
2022-08-27 05:21:53 +02:00
if (process.env.NODE_ENV !== 'production') {
2022-11-22 07:32:55 +01:00
global[REDIS] = client;
2022-08-27 05:21:53 +02:00
}
log('Redis initialized');
2022-11-22 07:32:55 +01:00
return client;
2022-08-28 06:38:35 +02:00
}
2022-08-27 05:21:53 +02:00
2022-10-07 00:00:16 +02:00
async function get(key) {
await connect();
2022-11-22 07:32:55 +01:00
const data = await redis.get(key);
log({ key, data });
try {
2022-11-22 07:32:55 +01:00
return JSON.parse(data);
} catch {
return null;
}
2022-10-07 00:00:16 +02:00
}
async function set(key, value) {
await connect();
return redis.set(key, JSON.stringify(value));
2022-10-07 00:00:16 +02:00
}
async function del(key) {
await connect();
return redis.del(key);
}
2022-10-07 00:00:16 +02:00
async function connect() {
if (!redis && enabled) {
2022-11-22 07:32:55 +01:00
redis = global[REDIS] || (await 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, del, DELETED };