memorium/lib/cache/cache.ts

50 lines
1.3 KiB
TypeScript

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);
console.log("Connected to redis");
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)) {
const cacheHit = await cache.sendCommand("GET", [id], {
returnUint8Arrays: true,
}) as T;
if (cacheHit) console.log("[cache] HIT ", { id });
else console.log("[cache] MISS", { id });
return cacheHit;
}
const cacheHit = await cache.get(id) as T;
if (cacheHit) console.log("[cache] HIT ", { id });
else console.log("[cache] MISS", { id });
return cacheHit;
}
export async function set<T extends RedisValue>(id: string, content: T) {
console.log("[cache] storing ", { id });
return await cache.set(id, content);
}