2022-08-29 19:47:31 +02:00
|
|
|
import debug from 'debug';
|
2022-11-01 07:42:37 +01:00
|
|
|
import Redis from 'ioredis';
|
2022-08-29 05:20:54 +02:00
|
|
|
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 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() {
|
2022-09-01 20:11:11 +02:00
|
|
|
if (!process.env.REDIS_URL) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2022-09-06 07:47:45 +02:00
|
|
|
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
|
|
|
}
|
|
|
|
|
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
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
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() {
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2022-11-08 01:22:49 +01:00
|
|
|
export default { enabled, client: redis, log, connect, get, set, del };
|