UNPKG

2.89 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.CacheInterceptor = void 0;
4const tslib_1 = require("tslib");
5const rxjs_1 = require("rxjs");
6const operators_1 = require("rxjs/operators");
7const decorators_1 = require("../../decorators");
8const shared_utils_1 = require("../../utils/shared.utils");
9const cache_constants_1 = require("../cache.constants");
10const HTTP_ADAPTER_HOST = 'HttpAdapterHost';
11const REFLECTOR = 'Reflector';
12let CacheInterceptor = class CacheInterceptor {
13 constructor(cacheManager, reflector) {
14 this.cacheManager = cacheManager;
15 this.reflector = reflector;
16 this.allowedMethods = ['GET'];
17 }
18 async intercept(context, next) {
19 var _a;
20 const key = this.trackBy(context);
21 const ttlValueOrFactory = (_a = this.reflector.get(cache_constants_1.CACHE_TTL_METADATA, context.getHandler())) !== null && _a !== void 0 ? _a : null;
22 if (!key) {
23 return next.handle();
24 }
25 try {
26 const value = await this.cacheManager.get(key);
27 if (!shared_utils_1.isNil(value)) {
28 return rxjs_1.of(value);
29 }
30 const ttl = shared_utils_1.isFunction(ttlValueOrFactory)
31 ? await ttlValueOrFactory(context)
32 : ttlValueOrFactory;
33 return next.handle().pipe(operators_1.tap(response => {
34 const args = shared_utils_1.isNil(ttl) ? [key, response] : [key, response, { ttl }];
35 this.cacheManager.set(...args);
36 }));
37 }
38 catch (_b) {
39 return next.handle();
40 }
41 }
42 trackBy(context) {
43 const httpAdapter = this.httpAdapterHost.httpAdapter;
44 const isHttpApp = httpAdapter && !!httpAdapter.getRequestMethod;
45 const cacheMetadata = this.reflector.get(cache_constants_1.CACHE_KEY_METADATA, context.getHandler());
46 if (!isHttpApp || cacheMetadata) {
47 return cacheMetadata;
48 }
49 const request = context.getArgByIndex(0);
50 if (!this.isRequestCacheable(context)) {
51 return undefined;
52 }
53 return httpAdapter.getRequestUrl(request);
54 }
55 isRequestCacheable(context) {
56 const req = context.switchToHttp().getRequest();
57 return this.allowedMethods.includes(req.method);
58 }
59};
60tslib_1.__decorate([
61 decorators_1.Optional(),
62 decorators_1.Inject(HTTP_ADAPTER_HOST),
63 tslib_1.__metadata("design:type", Object)
64], CacheInterceptor.prototype, "httpAdapterHost", void 0);
65CacheInterceptor = tslib_1.__decorate([
66 decorators_1.Injectable(),
67 tslib_1.__param(0, decorators_1.Inject(cache_constants_1.CACHE_MANAGER)),
68 tslib_1.__param(1, decorators_1.Inject(REFLECTOR)),
69 tslib_1.__metadata("design:paramtypes", [Object, Object])
70], CacheInterceptor);
71exports.CacheInterceptor = CacheInterceptor;