UNPKG

@zlattice/lattice-js

Version:

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

68 lines 2.36 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CacheService = void 0; const logger_1 = require("../logger.js"); const redis_1 = __importDefault(require("@keyv/redis")); const cacheable_1 = require("cacheable"); class CacheService { constructor(config) { const { backend, defaultTtl, redisUrl, namespace } = config; switch (backend) { case "memory": this.cache = new cacheable_1.Cacheable({ ttl: defaultTtl }); break; case "redis": { const primary = new redis_1.default(config.redisUrl || "redis://localhost:6379/0", { namespace: namespace || "zlattice", keyPrefixSeparator: ":" }); primary.on("error", (err) => { logger_1.log.error(`Redis connection error: ${err}`); }); primary.on("connect", () => { logger_1.log.info("Redis connected"); }); this.cache = new cacheable_1.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(); } } exports.CacheService = CacheService; //# sourceMappingURL=cache.js.map