Files
epirent-cache-proxy/dist/cache.js

37 lines
867 B
JavaScript

import { LRUCache } from "lru-cache";
import config from "./config.js";
let redis = null;
let useRedis = false;
export async function initCache() {
if (config.redisUrl) {
const { createClient } = await import("redis");
redis = createClient({ url: config.redisUrl });
await redis.connect();
useRedis = true;
}
}
const lru = new LRUCache({ max: 1000 });
export async function get(key) {
if (useRedis) {
const raw = await redis.get(key);
return raw ? JSON.parse(raw) : null;
}
return lru.get(key) ?? null;
}
export async function set(key, val) {
if (useRedis) {
await redis.set(key, JSON.stringify(val));
}
else {
lru.set(key, val);
}
}
export async function del(key) {
if (useRedis) {
await redis.del(key);
}
else {
lru.delete(key);
}
}