UNPKG

cache-panda

Version:

🐼 A flexible, decorator-based smart cache module for NestJS with TTL, key prefixing, and conditional caching based on method execution time.

70 lines 3.19 kB
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var __param = (this && this.__param) || function (paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } }; var CachePandaService_1; Object.defineProperty(exports, "__esModule", { value: true }); exports.CachePandaService = void 0; const common_1 = require("@nestjs/common"); const cache_manager_1 = require("@nestjs/cache-manager"); let CachePandaService = CachePandaService_1 = class CachePandaService { constructor(cacheManager) { this.cacheManager = cacheManager; this.logger = new common_1.Logger(CachePandaService_1.name); CachePandaService_1.instance = this; } static getInstance() { if (!CachePandaService_1.instance) { throw new Error("[cache-panda] CachePandaService not initialized. Ensure CachePanda.register() is added to your module."); } return CachePandaService_1.instance; } async getCache(key) { return this.cacheManager.get(key); } async setCache(key, value, ttl) { if (!ttl) return await this.cacheManager.set(key, value); return await this.cacheManager.set(key, value, ttl); } async deleteCache(key) { await this.cacheManager.del(key); } async clearCache() { await this.cacheManager.reset(); } async deleteCacheByKeys(keys) { for (const key of keys) { await this.cacheManager.del(key); this.logger.log(`Deleted cache key: ${key}`); } } async getKeysByKeyPattern(pattern) { const store = this.cacheManager.store; if (typeof store.keys !== "function") { throw new Error("[cache-panda] Cache store does not support key scanning"); } const keys = await store.keys(); return keys.filter((key) => key.includes(pattern)); } async deleteCacheByKeyPattern(pattern) { const keys = await this.getKeysByKeyPattern(pattern); await Promise.all(keys.map((key) => this.deleteCache(key))); } }; CachePandaService = CachePandaService_1 = __decorate([ (0, common_1.Injectable)(), __param(0, (0, common_1.Inject)(cache_manager_1.CACHE_MANAGER)), __metadata("design:paramtypes", [Object]) ], CachePandaService); exports.CachePandaService = CachePandaService; //# sourceMappingURL=cache-panda.service.js.map