UNPKG

@amirmarmul/waba-common

Version:

![GitHub release](https://img.shields.io/github/v/release/amirmarmul/waba-common?style=flat-square)

52 lines (51 loc) 1.42 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RedisCache = void 0; const ioredis_1 = require("ioredis"); const DEFAULT_NAMESPACE = "waba"; const DEFAULT_CACHE_TIME_IN_SECONDS = 30; const EXPIRY_MODE = "EX"; /** * @deprecated */ class RedisCache { TTL; redis; namespace; constructor() { this.redis = new ioredis_1.Redis(process.env.REDIS_URL); this.TTL = DEFAULT_CACHE_TIME_IN_SECONDS; this.namespace = DEFAULT_NAMESPACE; } async get(key) { key = this.getCacheKey(key); try { const cached = await this.redis.get(key); if (cached) { return JSON.parse(cached); } } catch (error) { await this.redis.del(key); } return null; } async set(key, data, ttl = this.TTL) { if (ttl === 0) { return; } await this.redis.set(this.getCacheKey(key), JSON.stringify(data), EXPIRY_MODE, ttl); } async invalidate(key) { const keys = await this.redis.keys(this.getCacheKey(key)); const pipeline = this.redis.pipeline(); keys.forEach(function (key) { pipeline.del(key); }); await pipeline.exec(); } getCacheKey(key) { return this.namespace ? `${this.namespace}:${key}` : key; } } exports.RedisCache = RedisCache;