UNPKG

@zlattice/lattice-js

Version:

Lattice blockchain TypeScript SDK with dual module support (CJS + ESM)

62 lines 2.02 kB
import { log } from "../logger.js"; import KeyvRedis from "@keyv/redis"; import { Cacheable } from "cacheable"; class CacheService { constructor(config) { const { backend, defaultTtl, redisUrl, namespace } = config; switch (backend) { case "memory": this.cache = new Cacheable({ ttl: defaultTtl }); break; case "redis": { const primary = new KeyvRedis(config.redisUrl || "redis://localhost:6379/0", { namespace: namespace || "zlattice", keyPrefixSeparator: ":" }); primary.on("error", (err) => { log.error(`Redis connection error: ${err}`); }); primary.on("connect", () => { log.info("Redis connected"); }); this.cache = new Cacheable({ primary, ttl: defaultTtl }); break; } default: throw new Error(`Unsupported cache backend: ${backend}`); } } static memory() { return new CacheService({ backend: "memory" }); } static redis(redisUrl) { return new CacheService({ backend: "redis", redisUrl }); } async set(key, value, ttl) { if (ttl) { await this.cache.set(key, JSON.stringify(value), ttl); } else { await this.cache.set(key, JSON.stringify(value)); } } async get(key) { const value = await this.cache.get(key); return value ? JSON.parse(value) : null; } async delete(key) { await this.cache.delete(key); } async exists(key) { return await this.cache.has(key); } async validate(key, value) { const storedValue = await this.cache.get(key); return storedValue === JSON.stringify(value); } async reset() { await this.cache.clear(); } } export { CacheService }; //# sourceMappingURL=cache.js.map