UNPKG

common-core-pkg

Version:

Common package for all the utils

107 lines 3.61 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RedisService = void 0; const ioredis_1 = require("ioredis"); class RedisService { constructor(db = 0, ttl = 0) { this.ttl = 60; this.baseConfig = { host: process.env.REDIS_HOST || "localhost", port: parseInt(process.env.REDIS_PORT || "6379"), }; if (ttl > 0) { this.ttl = ttl; } this.client = new ioredis_1.default({ ...this.baseConfig, db, lazyConnect: false, retryStrategy: (times) => { const delay = Math.min(times * 50, 2000); return delay; }, }); this.client.on("connect", () => { console.log(`Connected to Redis DB ${db}`); }); this.client.on("error", (err) => { console.error(`Redis DB ${db} error:`, err.message); }); } async set(key, value, ttlSeconds) { const ttlToUse = ttlSeconds ?? this.ttl; await this.client.set(key, JSON.stringify(value), "EX", ttlToUse); } async get(key) { const val = await this.client.get(key); return val ? JSON.parse(val) : null; } async del(key) { return await this.client.del(key); } async exists(key) { const result = await this.client.exists(key); return result === 1; } async ttlKey(key) { return await this.client.ttl(key); } async mget(keys) { if (keys.length === 0) return []; const values = await this.client.mget(...keys); return values.map((val) => (val ? JSON.parse(val) : null)); } async disconnect() { await this.client.quit(); } getClient() { return this.client; } async fetchIfNot(key, callback) { const exists = await this.get(key); if (!exists) return await callback(); return exists; } async delByPatternPipeline(pattern, batchSize = 100) { let cursor = "0"; let deletedCount = 0; do { const [nextCursor, keys] = await this.client.scan(cursor, "MATCH", pattern, "COUNT", batchSize); cursor = nextCursor; if (keys.length > 0) { const pipeline = this.client.pipeline(); keys.forEach((key) => pipeline.del(key)); const results = await pipeline.exec(); deletedCount += results?.filter(([err, result]) => !err && result === 1).length || 0; } } while (cursor !== "0"); return deletedCount; } async delByPattern(pattern, batchSize = 100) { let cursor = "0"; let deletedCount = 0; const keysToDelete = []; do { const [nextCursor, keys] = await this.client.scan(cursor, "MATCH", pattern, "COUNT", batchSize); cursor = nextCursor; if (keys.length > 0) { keysToDelete.push(...keys); if (keysToDelete.length >= batchSize) { const deleted = await this.client.del(...keysToDelete); deletedCount += deleted; keysToDelete.length = 0; } } } while (cursor !== "0"); if (keysToDelete.length > 0) { const deleted = await this.client.del(...keysToDelete); deletedCount += deleted; } return deletedCount; } } exports.RedisService = RedisService; //# sourceMappingURL=redis.service.js.map