UNPKG

dino-core

Version:

A dependency injection framework for NodeJS applications

82 lines 3.39 kB
"use strict"; // Copyright 2021 Quirino Brizi [quirino.brizi@gmail.com] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", { value: true }); exports.CacheInterceptor = void 0; const promise_helper_1 = require("../../../helper/promise.helper"); const cache_key_generator_1 = require("../../cache/cache.key.generator"); const cache_manager_1 = require("../../cache/cache.manager"); const abstract_interceptors_1 = require("./abstract.interceptors"); /** * Implement an "around" interceptor that provide caching functionalities */ class CacheInterceptor extends abstract_interceptors_1.AbstractInterceptor { constructor() { super(); this.cacheManager = new cache_manager_1.CacheManager(); this.cacheKeyGenerator = cache_key_generator_1.CacheKeyGenerator.create(); } intercept(obj, prop) { const cacheContext = obj.cacheable !== undefined ? obj.cacheable() : null; return (...args) => { let answer = this.get(cacheContext, [...args, prop]); if (answer == null || answer === undefined) { // no cache element found proceed on the chain to retrieve information answer = obj[prop].bind(obj)(...args); if (promise_helper_1.PromiseHelper.isAPromise(answer)) { return answer.then((data) => this.set(cacheContext, data, [...args, prop])); } else { this.set(cacheContext, answer, [...args, prop]); } } return answer; }; } isApplicable(obj, prop) { const cacheContext = obj.cacheable !== undefined ? obj.cacheable() : undefined; if (typeof obj[prop] !== 'function') { return false; } if (cacheContext == null) { return false; } return cacheContext?.isCacheActivatedFor(prop); } get(cacheContext, ...args) { if (cacheContext == null) { return null; } const cacheName = cacheContext.getCacheName(); const key = this.cacheKeyGenerator.generate(...args); return this.cacheManager.get(cacheName, key, cacheContext.getCacheOptions()); } set(cacheContext, data, ...args) { if (cacheContext == null) { return data; } const cacheName = cacheContext.getCacheName(); const key = this.cacheKeyGenerator.generate(...args); this.cacheManager.store(cacheName, key, data, cacheContext.getCacheOptions()); return data; } static create() { if (CacheInterceptor._instance === undefined) { CacheInterceptor._instance = new CacheInterceptor(); } return CacheInterceptor._instance; } } exports.CacheInterceptor = CacheInterceptor; //# sourceMappingURL=cache.interceptor.js.map