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.

55 lines 2.8 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.CachePandaSet = void 0; const cache_constants_1 = require("../constants/cache.constants"); const XXH = __importStar(require("xxhashjs")); const reduce_args_util_1 = require("../utils/reduce-args.util"); const cache_panda_service_1 = require("../services/cache-panda.service"); function CachePandaSet(cacheOptions) { return (target, propertyKey, descriptor) => { const originalMethod = descriptor.value; descriptor.value = async function (...args) { const { ttl, prefix, name, argsIndex, executionTimeLimit = 0, } = cacheOptions; const cachePandaService = cache_panda_service_1.CachePandaService.getInstance(); const argsKey = (0, reduce_args_util_1.reduceArgsArrayToString)(args, argsIndex, "_"); const hash = XXH.h32(JSON.stringify({ method: propertyKey, args }), cache_constants_1.CACHE_KEY_HASH_SEED).toString(); const keyParts = [prefix, name, argsKey, hash].filter(Boolean); const cacheKey = keyParts.join(":"); const cachedResult = await cachePandaService.getCache(cacheKey); if (cachedResult) return JSON.parse(cachedResult); const startTime = performance.now(); const result = await originalMethod.apply(this, args); const execTime = performance.now() - startTime; if (execTime >= executionTimeLimit) { await cachePandaService.setCache(cacheKey, JSON.stringify(result), ttl); } return result; }; }; } exports.CachePandaSet = CachePandaSet; //# sourceMappingURL=cache-panda-set.decorator.js.map