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();
|
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-11-22 07:32:55 +01:00
|
|
|
async function getClient() {
|
|
|
|
if (!process.env.REDIS_URL) {
|
2022-09-01 20:11:11 +02:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-11-22 07:32:55 +01:00
|
|
|
const client = createClient({ url: process.env.REDIS_URL });
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2022-09-05 20:36:57 +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 });
|
|
|
|
|
2022-11-09 07:58:52 +01:00
|
|
|
try {
|
2022-11-22 07:32:55 +01:00
|
|
|
return JSON.parse(data);
|
2022-11-09 07:58:52 +01:00
|
|
|
} catch {
|
|
|
|
return null;
|
|
|
|
}
|
2022-10-07 00:00:16 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function set(key, value) {
|
|
|
|
await connect();
|
|
|
|
|
2022-11-08 07:35:51 +01:00
|
|
|
return redis.set(key, JSON.stringify(value));
|
2022-10-07 00:00:16 +02:00
|
|
|
}
|
|
|
|
|
2022-11-08 01:22:49 +01:00
|
|
|
async function del(key) {
|
|
|
|
await connect();
|
|
|
|
|
|
|
|
return redis.del(key);
|
|
|
|
}
|
|
|
|
|
2022-10-07 00:00:16 +02:00
|
|
|
async function connect() {
|
2022-11-09 07:58:52 +01:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2022-11-08 01:22:49 +01:00
|
|
|
export default { enabled, client: redis, log, connect, get, set, del };
|