2023-07-30 18:27:45 +02:00
|
|
|
import {
|
|
|
|
connect,
|
|
|
|
Redis,
|
|
|
|
RedisConnectOptions,
|
|
|
|
RedisValue,
|
|
|
|
} from "https://deno.land/x/redis@v0.31.0/mod.ts";
|
|
|
|
|
|
|
|
const REDIS_HOST = Deno.env.get("REDIS_HOST");
|
|
|
|
const REDIS_PASS = Deno.env.get("REDIS_PASS") || "";
|
|
|
|
const REDIS_PORT = Deno.env.get("REDIS_PORT");
|
|
|
|
|
|
|
|
async function createCache<T>(): Promise<Map<string, T> | Redis> {
|
|
|
|
if (REDIS_HOST) {
|
|
|
|
const conf: RedisConnectOptions = {
|
|
|
|
hostname: REDIS_HOST,
|
|
|
|
port: REDIS_PORT || 6379,
|
|
|
|
};
|
|
|
|
if (REDIS_PASS) {
|
|
|
|
conf.password = REDIS_PASS;
|
|
|
|
}
|
|
|
|
const client = await connect(conf);
|
2023-08-01 18:35:35 +02:00
|
|
|
console.log("[redis] connected");
|
2023-07-30 18:27:45 +02:00
|
|
|
return client;
|
|
|
|
}
|
|
|
|
|
|
|
|
return new Map<string, T>();
|
|
|
|
}
|
|
|
|
|
|
|
|
const cache = await createCache();
|
|
|
|
|
|
|
|
export async function get<T>(id: string, binary = false) {
|
|
|
|
if (binary && !(cache instanceof Map)) {
|
2023-08-01 03:15:15 +02:00
|
|
|
const cacheHit = await cache.sendCommand("GET", [id], {
|
2023-07-30 18:27:45 +02:00
|
|
|
returnUint8Arrays: true,
|
|
|
|
}) as T;
|
2023-08-01 03:15:15 +02:00
|
|
|
return cacheHit;
|
2023-07-30 18:27:45 +02:00
|
|
|
}
|
2023-08-01 03:15:15 +02:00
|
|
|
const cacheHit = await cache.get(id) as T;
|
|
|
|
return cacheHit;
|
2023-07-30 18:27:45 +02:00
|
|
|
}
|
2023-08-01 18:35:35 +02:00
|
|
|
export function clearAll() {
|
|
|
|
if ("flushall" in cache) {
|
|
|
|
return cache.flushall();
|
|
|
|
} else {
|
|
|
|
for (const k of cache.keys()) {
|
|
|
|
cache.delete(k);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function expire(id: string, seconds: number) {
|
|
|
|
if ("expire" in cache) {
|
|
|
|
return cache.expire(id, seconds);
|
|
|
|
}
|
|
|
|
}
|
2023-07-30 18:27:45 +02:00
|
|
|
|
|
|
|
export async function set<T extends RedisValue>(id: string, content: T) {
|
2023-08-01 03:15:15 +02:00
|
|
|
console.log("[cache] storing ", { id });
|
2023-07-30 18:27:45 +02:00
|
|
|
return await cache.set(id, content);
|
|
|
|
}
|