UNPKG

@squareboat/nest-cache

Version:

The cache package for your NestJS Applications

83 lines (82 loc) 3.1 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.InMemoryDriver = void 0; const loadPackage_1 = require("../utils/loadPackage"); class InMemoryDriver { constructor(options) { this.options = options; const NodeCache = (0, loadPackage_1.loadPackage)("node-cache", "@squareboat/nest-cache"); this.client = new NodeCache({ stdTTL: 100, checkperiod: 120 }); } get(key) { return __awaiter(this, void 0, void 0, function* () { const cacheKey = `${this.options.prefix}:::${key}`; return this.client.get(cacheKey); }); } set(key, value, ttlInSec) { return __awaiter(this, void 0, void 0, function* () { const cacheKey = `${this.options.prefix}:::${key}`; if (ttlInSec) { return this.client.set(cacheKey, value, ttlInSec); } return this.client.set(cacheKey, value); }); } has(key) { return __awaiter(this, void 0, void 0, function* () { const cacheKey = `${this.options.prefix}:::${key}`; return this.client.has(cacheKey); }); } remember(key, cb, ttlInSec) { return __awaiter(this, void 0, void 0, function* () { const exists = yield this.has(key); if (exists) return this.get(key); try { const response = yield cb(); yield this.set(key, response); return response; } catch (e) { throw e; } }); } rememberForever(key, cb) { return __awaiter(this, void 0, void 0, function* () { const exists = yield this.has(key); if (exists) return this.get(key); try { const response = yield cb(); yield this.set(key, response); return response; } catch (e) { throw e; } }); } forget(key) { return __awaiter(this, void 0, void 0, function* () { const cacheKey = `${this.options.prefix}:::${key}`; yield this.client.del(cacheKey); throw new Error("Method not implemented."); }); } getClient() { return this.client; } } exports.InMemoryDriver = InMemoryDriver;