@tsed/platform-cache 7.0.0-beta.7 → 7.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UseCache = void 0;
4
- const core_1 = require("@tsed/core");
5
4
  const di_1 = require("@tsed/di");
6
5
  const PlatformCacheInterceptor_1 = require("../interceptors/PlatformCacheInterceptor");
7
6
  function UseCache(options = {}) {
8
- return (0, core_1.useDecorators)((0, di_1.Intercept)(PlatformCacheInterceptor_1.PlatformCacheInterceptor, options));
7
+ return (0, di_1.Intercept)(PlatformCacheInterceptor_1.PlatformCacheInterceptor, options);
9
8
  }
10
9
  exports.UseCache = UseCache;
11
10
  //# sourceMappingURL=useCache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useCache.js","sourceRoot":"","sources":["../../../src/decorators/useCache.ts"],"names":[],"mappings":";;;AAAA,qCAAyC;AACzC,iCAAmC;AACnC,uFAAkF;AAGlF,SAAgB,QAAQ,CAAC,UAAgC,EAAE;IACzD,OAAO,IAAA,oBAAa,EAAC,IAAA,cAAS,EAAC,mDAAwB,EAAE,OAAO,CAAC,CAAC,CAAC;AACrE,CAAC;AAFD,4BAEC","sourcesContent":["import {useDecorators} from \"@tsed/core\";\nimport {Intercept} from \"@tsed/di\";\nimport {PlatformCacheInterceptor} from \"../interceptors/PlatformCacheInterceptor\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\n\nexport function UseCache(options: PlatformCacheOptions = {}) {\n return useDecorators(Intercept(PlatformCacheInterceptor, options));\n}\n"]}
1
+ {"version":3,"file":"useCache.js","sourceRoot":"","sources":["../../../src/decorators/useCache.ts"],"names":[],"mappings":";;;AAAA,iCAAmC;AACnC,uFAAkF;AAGlF,SAAgB,QAAQ,CAAC,UAAgC,EAAE;IACzD,OAAO,IAAA,cAAS,EAAC,mDAAwB,EAAE,OAAO,CAAC,CAAC;AACtD,CAAC;AAFD,4BAEC","sourcesContent":["import {Intercept} from \"@tsed/di\";\nimport {PlatformCacheInterceptor} from \"../interceptors/PlatformCacheInterceptor\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\n\nexport function UseCache(options: PlatformCacheOptions = {}) {\n return Intercept(PlatformCacheInterceptor, options);\n}\n"]}
@@ -5,6 +5,7 @@ const tslib_1 = require("tslib");
5
5
  const core_1 = require("@tsed/core");
6
6
  const di_1 = require("@tsed/di");
7
7
  const json_mapper_1 = require("@tsed/json-mapper");
8
+ const logger_1 = require("@tsed/logger");
8
9
  const schema_1 = require("@tsed/schema");
9
10
  const http_1 = require("http");
10
11
  const PlatformCache_1 = require("../services/PlatformCache");
@@ -22,6 +23,8 @@ const cleanHeaders = (headers) => {
22
23
  * @platform
23
24
  */
24
25
  let PlatformCacheInterceptor = class PlatformCacheInterceptor {
26
+ cache;
27
+ logger;
25
28
  async intercept(context, next) {
26
29
  if (this.cache.disabled()) {
27
30
  return next();
@@ -46,23 +49,27 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
46
49
  async cacheMethod(context, next) {
47
50
  const { type, ttl, collectionType, refreshThreshold, keyArgs, args } = this.getOptions(context);
48
51
  const key = [(0, core_1.nameOf)(context.target), context.propertyKey, keyArgs].join(":");
49
- const cachedObject = await this.cache.getCachedObject(key);
50
52
  const set = (result) => {
51
53
  const calculatedTTL = this.cache.calculateTTL(result, ttl);
52
54
  const data = (0, json_mapper_1.serialize)(result, { type, collectionType });
53
55
  this.cache.setCachedObject(key, data, { args, ttl: calculatedTTL });
54
56
  };
57
+ const cachedObject = await this.cache.getCachedObject(key);
58
+ if (!cachedObject) {
59
+ const result = await next();
60
+ set(result);
61
+ return result;
62
+ }
55
63
  this.canRefreshInBackground(key, { refreshThreshold, ttl }, async () => {
56
64
  const result = await next();
57
65
  await set(result);
58
- });
59
- if (cachedObject) {
60
- const { data } = cachedObject;
61
- return (0, json_mapper_1.deserialize)(JSON.parse(data), { collectionType, type });
62
- }
63
- const result = await next();
64
- setTimeout(() => set(result));
65
- return result;
66
+ }).catch((er) => this.logger.error({
67
+ event: "CACHE_ERROR",
68
+ method: "cacheMethod",
69
+ error: er
70
+ }));
71
+ const { data } = cachedObject;
72
+ return (0, json_mapper_1.deserialize)(JSON.parse(data), { collectionType, type });
66
73
  }
67
74
  async cacheResponse(context, next) {
68
75
  const $ctx = context.args[context.args.length - 1];
@@ -143,6 +150,10 @@ tslib_1.__decorate([
143
150
  (0, di_1.Inject)(),
144
151
  tslib_1.__metadata("design:type", PlatformCache_1.PlatformCache)
145
152
  ], PlatformCacheInterceptor.prototype, "cache", void 0);
153
+ tslib_1.__decorate([
154
+ (0, di_1.Inject)(),
155
+ tslib_1.__metadata("design:type", logger_1.Logger)
156
+ ], PlatformCacheInterceptor.prototype, "logger", void 0);
146
157
  PlatformCacheInterceptor = tslib_1.__decorate([
147
158
  (0, di_1.Interceptor)()
148
159
  ], PlatformCacheInterceptor);
@@ -1 +1 @@
1
- {"version":3,"file":"PlatformCacheInterceptor.js","sourceRoot":"","sources":["../../../src/interceptors/PlatformCacheInterceptor.ts"],"names":[],"mappings":";;;;AAAA,qCAA4D;AAC5D,iCAA8H;AAC9H,mDAAyD;AACzD,yCAA6C;AAC7C,+BAAqD;AAGrD,6DAAwD;AAExD,MAAM,YAAY,GAAG,CAAC,OAAgC,EAAE,EAAE;IACxD,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;SAC3B,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,gBAAgB,EAAE,cAAc,EAAE,eAAe,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;SACrF,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QAChC,OAAO;YACL,GAAG,OAAO;YACV,CAAC,GAAG,CAAC,EAAE,KAAK;SACb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BAAwB;IADpC,IAAA,gBAAW,GAAE;GACD,wBAAwB,CAmKpC;AAnKY,4DAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL < calculatedTTL - refreshThreshold) {\n await next();\n }\n\n await this.deleteKeyFromQueue(key);\n }\n }\n\n async cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {type, ttl, collectionType, refreshThreshold, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n const set = (result: any) => {\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n const data = serialize(result, {type, collectionType});\n this.cache.setCachedObject(key, data, {args, ttl: calculatedTTL});\n };\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n await set(result);\n });\n\n if (cachedObject) {\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n const result = await next();\n\n setTimeout(() => set(result));\n\n return result;\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs};\n }\n\n protected isEndpoint({target, propertyKey}: InterceptorContext<any, PlatformCacheOptions>) {\n return Store.fromMethod(target, propertyKey).has(JsonEntityStore);\n }\n\n protected async hasKeyInQueue(key: string) {\n return !!(await this.cache.get(`$$queue:${key}`));\n }\n\n protected async addKeyToQueue(key: string) {\n await this.cache.set(`$$queue:${key}`, true, {ttl: 120});\n }\n\n protected async deleteKeyFromQueue(key: string) {\n await this.cache.del(`$$queue:${key}`);\n }\n\n protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext) {\n const {headers, ttl} = cachedObject;\n const {request, response} = $ctx;\n\n const requestEtag = request.get(\"if-none-match\");\n\n if (requestEtag && headers.etag === requestEtag) {\n response.status(304).setHeaders(headers).body(undefined);\n\n return undefined;\n }\n\n const data = JSON.parse(cachedObject.data);\n\n $ctx.response\n .setHeaders({\n ...headers,\n \"x-cached\": \"true\",\n \"cache-control\": `max-age=${ttl}`\n })\n .body(data);\n\n return data;\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformCacheInterceptor.js","sourceRoot":"","sources":["../../../src/interceptors/PlatformCacheInterceptor.ts"],"names":[],"mappings":";;;;AAAA,qCAA4D;AAC5D,iCAA8H;AAC9H,mDAAyD;AACzD,yCAAoC;AACpC,yCAA6C;AAC7C,+BAAqD;AAGrD,6DAAwD;AAExD,MAAM,YAAY,GAAG,CAAC,OAAgC,EAAE,EAAE;IACxD,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;SAC3B,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,gBAAgB,EAAE,cAAc,EAAE,eAAe,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;SACrF,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QAChC,OAAO;YACL,GAAG,OAAO;YACV,CAAC,GAAG,CAAC,EAAE,KAAK;SACb,CAA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AAE,WAAW,GAAG,EAAE;SAClC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;QAEd,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAA;AA1KC;IADC,IAAA,WAAM,GAAE;sCACQ,6BAAa;uDAAC;AAG/B;IADC,IAAA,WAAM,GAAE;sCACS,eAAM;wDAAC;AALd,wBAAwB;IADpC,IAAA,gBAAW,GAAE;GACD,wBAAwB,CA4KpC;AA5KY,4DAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {Logger} from \"@tsed/logger\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n @Inject()\n protected logger: Logger;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL < calculatedTTL - refreshThreshold) {\n await next();\n }\n\n await this.deleteKeyFromQueue(key);\n }\n }\n\n async cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {type, ttl, collectionType, refreshThreshold, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const set = (result: any) => {\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n const data = serialize(result, {type, collectionType});\n this.cache.setCachedObject(key, data, {args, ttl: calculatedTTL});\n };\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (!cachedObject) {\n const result = await next();\n\n set(result);\n\n return result;\n }\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n await set(result);\n }).catch((er) =>\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"cacheMethod\",\n error: er\n })\n );\n\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs};\n }\n\n protected isEndpoint({target, propertyKey}: InterceptorContext<any, PlatformCacheOptions>) {\n return Store.fromMethod(target, propertyKey).has(JsonEntityStore);\n }\n\n protected async hasKeyInQueue(key: string) {\n return !!(await this.cache.get(`$$queue:${key}`));\n }\n\n protected async addKeyToQueue(key: string) {\n await this.cache.set(`$$queue:${key}`, true, {ttl: 120});\n }\n\n protected async deleteKeyFromQueue(key: string) {\n await this.cache.del(`$$queue:${key}`);\n }\n\n protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext) {\n const {headers, ttl} = cachedObject;\n const {request, response} = $ctx;\n\n const requestEtag = request.get(\"if-none-match\");\n\n if (requestEtag && headers.etag === requestEtag) {\n response.status(304).setHeaders(headers).body(undefined);\n\n return undefined;\n }\n\n const data = JSON.parse(cachedObject.data);\n\n $ctx.response\n .setHeaders({\n ...headers,\n \"x-cached\": \"true\",\n \"cache-control\": `max-age=${ttl}`\n })\n .body(data);\n\n return data;\n }\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- var _PlatformCache_cache;
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
3
  exports.PlatformCache = void 0;
5
4
  const tslib_1 = require("tslib");
@@ -14,17 +13,18 @@ const defaultKeyResolver = (args) => {
14
13
  * @platform
15
14
  */
16
15
  let PlatformCache = class PlatformCache {
17
- constructor() {
18
- _PlatformCache_cache.set(this, void 0);
19
- }
16
+ settings;
17
+ injector;
18
+ logger;
19
+ #cache;
20
20
  get cache() {
21
- return tslib_1.__classPrivateFieldGet(this, _PlatformCache_cache, "f");
21
+ return this.#cache;
22
22
  }
23
23
  async $onInit() {
24
24
  const settings = this.settings.get("cache");
25
25
  if (settings) {
26
- tslib_1.__classPrivateFieldSet(this, _PlatformCache_cache, await this.createCacheManager(settings), "f");
27
- await this.injector.emit("$onCreateCacheManager", tslib_1.__classPrivateFieldGet(this, _PlatformCache_cache, "f"));
26
+ this.#cache = await this.createCacheManager(settings);
27
+ await this.injector.emit("$onCreateCacheManager", this.#cache);
28
28
  }
29
29
  }
30
30
  disabled() {
@@ -46,19 +46,16 @@ let PlatformCache = class PlatformCache {
46
46
  }
47
47
  }
48
48
  wrap(key, fetch, options) {
49
- var _a;
50
49
  if (!this.cache) {
51
50
  return fetch();
52
51
  }
53
- return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.wrap(key, fetch, options);
52
+ return this.cache?.wrap(key, fetch, options);
54
53
  }
55
54
  async get(key, options = {}) {
56
- var _a;
57
- return (0, json_mapper_1.deserialize)((_a = this.cache) === null || _a === void 0 ? void 0 : _a.get(key), options);
55
+ return (0, json_mapper_1.deserialize)(this.cache?.get(key), options);
58
56
  }
59
57
  async set(key, value, options) {
60
- var _a;
61
- return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.set(key, value, options);
58
+ return this.cache?.set(key, value, options);
62
59
  }
63
60
  async getCachedObject(key) {
64
61
  try {
@@ -90,13 +87,11 @@ let PlatformCache = class PlatformCache {
90
87
  }
91
88
  }
92
89
  async del(key) {
93
- var _a;
94
- await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.del(key));
90
+ await this.cache?.del(key);
95
91
  }
96
92
  async reset() {
97
- var _a;
98
93
  // @ts-ignore
99
- await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.reset());
94
+ await this.cache?.reset();
100
95
  }
101
96
  async keys(...args) {
102
97
  if (this.cache && "store" in this.cache && this.cache.store.keys) {
@@ -118,7 +113,7 @@ let PlatformCache = class PlatformCache {
118
113
  const { caches, store = "memory", ttl, ...props } = settings;
119
114
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
120
115
  const { default: cacheManager } = await Promise.resolve().then(() => tslib_1.__importStar(require("cache-manager")));
121
- return (caches === null || caches === void 0 ? void 0 : caches.length)
116
+ return caches?.length
122
117
  ? cacheManager.multiCaching(caches, { ...props })
123
118
  : cacheManager.caching({
124
119
  ...props,
@@ -127,7 +122,6 @@ let PlatformCache = class PlatformCache {
127
122
  });
128
123
  }
129
124
  };
130
- _PlatformCache_cache = new WeakMap();
131
125
  tslib_1.__decorate([
132
126
  (0, di_1.Configuration)(),
133
127
  tslib_1.__metadata("design:type", Object)
@@ -1 +1 @@
1
- {"version":3,"file":"PlatformCache.js","sourceRoot":"","sources":["../../../src/services/PlatformCache.ts"],"names":[],"mappings":";;;;;AAAA,qCAA+C;AAC/C,iCAAwE;AACxE,mDAAkF;AAIlF,yCAAoC;AAEpC,MAAM,kBAAkB,GAAG,CAAC,IAAW,EAAE,EAAE;IACzC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,CAAC,IAAA,cAAO,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAA,uBAAS,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjG,CAAC,CAAC;AAIF;;GAEG;AAEH,IAAa,aAAa,GAA1B,MAAa,aAAa;IAA1B;QAUE,uCAAiC;IAsInC,CAAC;IApIC,IAAI,KAAK;QACP,OAAO,+BAAA,IAAI,4BAAO,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAwB,OAAO,CAAC,CAAC;QAEnE,IAAI,QAAQ,EAAE;YACZ,+B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AAO,CAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,MAAM;YACnB,CAAC,CAAC,YAAY,CAAC,YAAY,CAAC,MAAM,EAAE,EAAC,GAAG,KAAK,EAAC,CAAC;YAC/C,CAAC,CAAC,YAAY,CAAC,OAAO,CAAC;gBACnB,GAAG,KAAK;gBACR,GAAG;gBACH,KAAK,EAAE,IAAA,iBAAU,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK;aACjD,CAAC,CAAC;IACT,CAAC;CACF,CAAA;;AA9IC;IADC,IAAA,kBAAa,GAAE;;+CACkB;AAGlC;IADC,IAAA,WAAM,GAAE;sCACW,oBAAe;+CAAC;AAGpC;IADC,IAAA,WAAM,GAAE;sCACS,eAAM;6CAAC;AARd,aAAa;IADzB,IAAA,WAAM,GAAE;GACI,aAAa,CAgJzB;AAhJY,sCAAa","sourcesContent":["import {isClass, isFunction} from \"@tsed/core\";\nimport {Configuration, Inject, InjectorService, Module} from \"@tsed/di\";\nimport {deserialize, JsonDeserializerOptions, serialize} from \"@tsed/json-mapper\";\nimport type {Cache, CachingConfig, MultiCache, TtlFunction} from \"cache-manager\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheSettings} from \"../interfaces/interfaces\";\nimport {Logger} from \"@tsed/logger\";\n\nconst defaultKeyResolver = (args: any[]) => {\n return args.map((arg: any) => (isClass(arg) ? JSON.stringify(serialize(arg)) : arg)).join(\":\");\n};\n\nexport type CacheManager = Cache | MultiCache;\n\n/**\n * @platform\n */\n@Module()\nexport class PlatformCache {\n @Configuration()\n protected settings: Configuration;\n\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected logger: Logger;\n\n #cache: CacheManager | undefined;\n\n get cache() {\n return this.#cache;\n }\n\n async $onInit() {\n const settings = this.settings.get<PlatformCacheSettings>(\"cache\");\n\n if (settings) {\n this.#cache = await this.createCacheManager(settings);\n\n await this.injector.emit(\"$onCreateCacheManager\", this.#cache);\n }\n }\n\n disabled(): boolean {\n return !this.settings.get<PlatformCacheSettings>(\"cache\");\n }\n\n defaultKeyResolver() {\n return this.settings.get<(args: any[], ctx?: any) => string>(\"cache.keyResolver\", defaultKeyResolver);\n }\n\n defaultTtl() {\n return this.settings.get<number | TtlFunction>(\"cache.ttl\");\n }\n\n calculateTTL(result?: any, currentTtl?: number | TtlFunction) {\n const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;\n\n return isFunction(ttl) ? ttl(result) : ttl;\n }\n\n async ttl(key: string) {\n if (this.cache && \"store\" in this.cache && this.cache.store.ttl) {\n return this.cache.store.ttl(key);\n }\n }\n\n wrap<T>(key: string, fetch: () => Promise<T>, options?: CachingConfig): Promise<T> {\n if (!this.cache) {\n return fetch();\n }\n\n return this.cache?.wrap<T>(key, fetch, options as any);\n }\n\n async get<T>(key: string, options: JsonDeserializerOptions = {}): Promise<T | undefined> {\n return deserialize(this.cache?.get<T>(key), options);\n }\n\n async set<T>(key: string, value: any, options?: CachingConfig): Promise<T | undefined> {\n return this.cache?.set<T>(key, value, options);\n }\n\n async getCachedObject(key: string) {\n try {\n return await this.get<PlatformCachedObject>(key);\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"getCachedObject\",\n error: er\n });\n }\n }\n\n async setCachedObject(key: string, data: any, opts: {ttl: number} & Record<string, any>) {\n try {\n await this.set<PlatformCachedObject>(\n key,\n {\n ...opts,\n data: JSON.stringify(data)\n },\n {\n ttl: opts.ttl\n }\n );\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"setCachedObject\",\n error: er\n });\n }\n }\n\n async del(key: string): Promise<void> {\n await this.cache?.del(key);\n }\n\n async reset(): Promise<void> {\n // @ts-ignore\n await this.cache?.reset();\n }\n\n async keys(...args: any[]): Promise<string[]> {\n if (this.cache && \"store\" in this.cache && this.cache.store.keys) {\n return this.cache.store.keys(...args);\n }\n\n // istanbul ignore next\n return [];\n }\n\n async getMatchingKeys(patterns: string): Promise<string[]> {\n const [keys, {default: micromatch}] = await Promise.all([this.keys(), import(\"micromatch\")]);\n\n return micromatch(keys, patterns);\n }\n\n async deleteMatchingKeys(patterns: string): Promise<string[]> {\n const keys = await this.getMatchingKeys(patterns);\n\n await Promise.all(keys.map((key: string) => this.del(key)));\n\n return keys;\n }\n\n protected async createCacheManager(settings: PlatformCacheSettings) {\n const {caches, store = \"memory\", ttl, ...props} = settings;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const {default: cacheManager} = await import(\"cache-manager\");\n\n return caches?.length\n ? cacheManager.multiCaching(caches, {...props})\n : cacheManager.caching({\n ...props,\n ttl,\n store: isFunction(store) ? await store() : store\n });\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformCache.js","sourceRoot":"","sources":["../../../src/services/PlatformCache.ts"],"names":[],"mappings":";;;;AAAA,qCAA+C;AAC/C,iCAAwE;AACxE,mDAAkF;AAIlF,yCAAoC;AAEpC,MAAM,kBAAkB,GAAG,CAAC,IAAW,EAAE,EAAE;IACzC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,CAAC,IAAA,cAAO,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,IAAA,uBAAS,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjG,CAAC,CAAC;AAIF;;GAEG;AAEH,IAAa,aAAa,GAA1B,MAAa,aAAa;IAEd,QAAQ,CAAgB;IAGxB,QAAQ,CAAkB;IAG1B,MAAM,CAAS;IAEzB,MAAM,CAA2B;IAEjC,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAwB,OAAO,CAAC,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AAC,CAAC,YAAY,CAAC,YAAY,CAAC,MAAM,EAAE,EAAC,GAAG,KAAK,EAAC,CAAC;YAC/C,CAAC,CAAC,YAAY,CAAC,OAAO,CAAC;gBACnB,GAAG,KAAK;gBACR,GAAG;gBACH,KAAK,EAAE,IAAA,iBAAU,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK;aACjD,CAAC,CAAC;IACT,CAAC;CACF,CAAA;AA9IC;IADC,IAAA,kBAAa,GAAE;;+CACkB;AAGlC;IADC,IAAA,WAAM,GAAE;sCACW,oBAAe;+CAAC;AAGpC;IADC,IAAA,WAAM,GAAE;sCACS,eAAM;6CAAC;AARd,aAAa;IADzB,IAAA,WAAM,GAAE;GACI,aAAa,CAgJzB;AAhJY,sCAAa","sourcesContent":["import {isClass, isFunction} from \"@tsed/core\";\nimport {Configuration, Inject, InjectorService, Module} from \"@tsed/di\";\nimport {deserialize, JsonDeserializerOptions, serialize} from \"@tsed/json-mapper\";\nimport type {Cache, CachingConfig, MultiCache, TtlFunction} from \"cache-manager\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheSettings} from \"../interfaces/interfaces\";\nimport {Logger} from \"@tsed/logger\";\n\nconst defaultKeyResolver = (args: any[]) => {\n return args.map((arg: any) => (isClass(arg) ? JSON.stringify(serialize(arg)) : arg)).join(\":\");\n};\n\nexport type CacheManager = Cache | MultiCache;\n\n/**\n * @platform\n */\n@Module()\nexport class PlatformCache {\n @Configuration()\n protected settings: Configuration;\n\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected logger: Logger;\n\n #cache: CacheManager | undefined;\n\n get cache() {\n return this.#cache;\n }\n\n async $onInit() {\n const settings = this.settings.get<PlatformCacheSettings>(\"cache\");\n\n if (settings) {\n this.#cache = await this.createCacheManager(settings);\n\n await this.injector.emit(\"$onCreateCacheManager\", this.#cache);\n }\n }\n\n disabled(): boolean {\n return !this.settings.get<PlatformCacheSettings>(\"cache\");\n }\n\n defaultKeyResolver() {\n return this.settings.get<(args: any[], ctx?: any) => string>(\"cache.keyResolver\", defaultKeyResolver);\n }\n\n defaultTtl() {\n return this.settings.get<number | TtlFunction>(\"cache.ttl\");\n }\n\n calculateTTL(result?: any, currentTtl?: number | TtlFunction) {\n const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;\n\n return isFunction(ttl) ? ttl(result) : ttl;\n }\n\n async ttl(key: string) {\n if (this.cache && \"store\" in this.cache && this.cache.store.ttl) {\n return this.cache.store.ttl(key);\n }\n }\n\n wrap<T>(key: string, fetch: () => Promise<T>, options?: CachingConfig): Promise<T> {\n if (!this.cache) {\n return fetch();\n }\n\n return this.cache?.wrap<T>(key, fetch, options as any);\n }\n\n async get<T>(key: string, options: JsonDeserializerOptions = {}): Promise<T | undefined> {\n return deserialize(this.cache?.get<T>(key), options);\n }\n\n async set<T>(key: string, value: any, options?: CachingConfig): Promise<T | undefined> {\n return this.cache?.set<T>(key, value, options);\n }\n\n async getCachedObject(key: string) {\n try {\n return await this.get<PlatformCachedObject>(key);\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"getCachedObject\",\n error: er\n });\n }\n }\n\n async setCachedObject(key: string, data: any, opts: {ttl: number} & Record<string, any>) {\n try {\n await this.set<PlatformCachedObject>(\n key,\n {\n ...opts,\n data: JSON.stringify(data)\n },\n {\n ttl: opts.ttl\n }\n );\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"setCachedObject\",\n error: er\n });\n }\n }\n\n async del(key: string): Promise<void> {\n await this.cache?.del(key);\n }\n\n async reset(): Promise<void> {\n // @ts-ignore\n await this.cache?.reset();\n }\n\n async keys(...args: any[]): Promise<string[]> {\n if (this.cache && \"store\" in this.cache && this.cache.store.keys) {\n return this.cache.store.keys(...args);\n }\n\n // istanbul ignore next\n return [];\n }\n\n async getMatchingKeys(patterns: string): Promise<string[]> {\n const [keys, {default: micromatch}] = await Promise.all([this.keys(), import(\"micromatch\")]);\n\n return micromatch(keys, patterns);\n }\n\n async deleteMatchingKeys(patterns: string): Promise<string[]> {\n const keys = await this.getMatchingKeys(patterns);\n\n await Promise.all(keys.map((key: string) => this.del(key)));\n\n return keys;\n }\n\n protected async createCacheManager(settings: PlatformCacheSettings) {\n const {caches, store = \"memory\", ttl, ...props} = settings;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const {default: cacheManager} = await import(\"cache-manager\");\n\n return caches?.length\n ? cacheManager.multiCaching(caches, {...props})\n : cacheManager.caching({\n ...props,\n ttl,\n store: isFunction(store) ? await store() : store\n });\n }\n}\n"]}
@@ -1,7 +1,6 @@
1
- import { useDecorators } from "@tsed/core";
2
1
  import { Intercept } from "@tsed/di";
3
2
  import { PlatformCacheInterceptor } from "../interceptors/PlatformCacheInterceptor.js";
4
3
  export function UseCache(options = {}) {
5
- return useDecorators(Intercept(PlatformCacheInterceptor, options));
4
+ return Intercept(PlatformCacheInterceptor, options);
6
5
  }
7
6
  //# sourceMappingURL=useCache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"useCache.js","sourceRoot":"","sources":["../../../src/decorators/useCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,aAAa,EAAC,MAAM,YAAY,CAAC;AACzC,OAAO,EAAC,SAAS,EAAC,MAAM,UAAU,CAAC;AACnC,OAAO,EAAC,wBAAwB,EAAC,MAAM,0CAA0C,CAAC;AAGlF,MAAM,UAAU,QAAQ,CAAC,UAAgC,EAAE;IACzD,OAAO,aAAa,CAAC,SAAS,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC,CAAC;AACrE,CAAC","sourcesContent":["import {useDecorators} from \"@tsed/core\";\nimport {Intercept} from \"@tsed/di\";\nimport {PlatformCacheInterceptor} from \"../interceptors/PlatformCacheInterceptor\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\n\nexport function UseCache(options: PlatformCacheOptions = {}) {\n return useDecorators(Intercept(PlatformCacheInterceptor, options));\n}\n"]}
1
+ {"version":3,"file":"useCache.js","sourceRoot":"","sources":["../../../src/decorators/useCache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,SAAS,EAAC,MAAM,UAAU,CAAC;AACnC,OAAO,EAAC,wBAAwB,EAAC,MAAM,0CAA0C,CAAC;AAGlF,MAAM,UAAU,QAAQ,CAAC,UAAgC,EAAE;IACzD,OAAO,SAAS,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC;AACtD,CAAC","sourcesContent":["import {Intercept} from \"@tsed/di\";\nimport {PlatformCacheInterceptor} from \"../interceptors/PlatformCacheInterceptor\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\n\nexport function UseCache(options: PlatformCacheOptions = {}) {\n return Intercept(PlatformCacheInterceptor, options);\n}\n"]}
@@ -2,6 +2,7 @@ import { __decorate, __metadata } from "tslib";
2
2
  import { isClass, isString, nameOf, Store } from "@tsed/core";
3
3
  import { DIContext, Inject, Interceptor } from "@tsed/di";
4
4
  import { deserialize, serialize } from "@tsed/json-mapper";
5
+ import { Logger } from "@tsed/logger";
5
6
  import { JsonEntityStore } from "@tsed/schema";
6
7
  import { IncomingMessage, ServerResponse } from "http";
7
8
  import { PlatformCache } from "../services/PlatformCache.js";
@@ -19,6 +20,8 @@ const cleanHeaders = (headers) => {
19
20
  * @platform
20
21
  */
21
22
  let PlatformCacheInterceptor = class PlatformCacheInterceptor {
23
+ cache;
24
+ logger;
22
25
  async intercept(context, next) {
23
26
  if (this.cache.disabled()) {
24
27
  return next();
@@ -43,23 +46,27 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
43
46
  async cacheMethod(context, next) {
44
47
  const { type, ttl, collectionType, refreshThreshold, keyArgs, args } = this.getOptions(context);
45
48
  const key = [nameOf(context.target), context.propertyKey, keyArgs].join(":");
46
- const cachedObject = await this.cache.getCachedObject(key);
47
49
  const set = (result) => {
48
50
  const calculatedTTL = this.cache.calculateTTL(result, ttl);
49
51
  const data = serialize(result, { type, collectionType });
50
52
  this.cache.setCachedObject(key, data, { args, ttl: calculatedTTL });
51
53
  };
54
+ const cachedObject = await this.cache.getCachedObject(key);
55
+ if (!cachedObject) {
56
+ const result = await next();
57
+ set(result);
58
+ return result;
59
+ }
52
60
  this.canRefreshInBackground(key, { refreshThreshold, ttl }, async () => {
53
61
  const result = await next();
54
62
  await set(result);
55
- });
56
- if (cachedObject) {
57
- const { data } = cachedObject;
58
- return deserialize(JSON.parse(data), { collectionType, type });
59
- }
60
- const result = await next();
61
- setTimeout(() => set(result));
62
- return result;
63
+ }).catch((er) => this.logger.error({
64
+ event: "CACHE_ERROR",
65
+ method: "cacheMethod",
66
+ error: er
67
+ }));
68
+ const { data } = cachedObject;
69
+ return deserialize(JSON.parse(data), { collectionType, type });
63
70
  }
64
71
  async cacheResponse(context, next) {
65
72
  const $ctx = context.args[context.args.length - 1];
@@ -140,6 +147,10 @@ __decorate([
140
147
  Inject(),
141
148
  __metadata("design:type", PlatformCache)
142
149
  ], PlatformCacheInterceptor.prototype, "cache", void 0);
150
+ __decorate([
151
+ Inject(),
152
+ __metadata("design:type", Logger)
153
+ ], PlatformCacheInterceptor.prototype, "logger", void 0);
143
154
  PlatformCacheInterceptor = __decorate([
144
155
  Interceptor()
145
156
  ], PlatformCacheInterceptor);
@@ -1 +1 @@
1
- {"version":3,"file":"PlatformCacheInterceptor.js","sourceRoot":"","sources":["../../../src/interceptors/PlatformCacheInterceptor.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAC,MAAM,YAAY,CAAC;AAC5D,OAAO,EAAc,SAAS,EAAE,MAAM,EAAE,WAAW,EAA0D,MAAM,UAAU,CAAC;AAC9H,OAAO,EAAC,WAAW,EAAE,SAAS,EAAC,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAC,eAAe,EAAC,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAC,eAAe,EAAE,cA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OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAEzD,OAAO,SAAS,CAAC;SAClB;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAE3C,IAAI,CAAC,QAAQ;aACV,UAAU,CAAC;YACV,GAAG,OAAO;YACV,UAAU,EAAE,MAAM;YAClB,eAAe,EAAE,WAAW,GAAG,EAAE;SAClC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;QAEd,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAA;AAjKC;IADC,MAAM,EAAE;8BACQ,aAAa;uDAAC;AAFpB,wBAAwB;IADpC,WAAW,EAAE;GACD,wBAAwB,CAmKpC;SAnKY,wBAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL < calculatedTTL - refreshThreshold) {\n await next();\n }\n\n await this.deleteKeyFromQueue(key);\n }\n }\n\n async cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {type, ttl, collectionType, refreshThreshold, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n const set = (result: any) => {\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n const data = serialize(result, {type, collectionType});\n this.cache.setCachedObject(key, data, {args, ttl: calculatedTTL});\n };\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n await set(result);\n });\n\n if (cachedObject) {\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n const result = await next();\n\n setTimeout(() => set(result));\n\n return result;\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs};\n }\n\n protected isEndpoint({target, propertyKey}: InterceptorContext<any, PlatformCacheOptions>) {\n return Store.fromMethod(target, propertyKey).has(JsonEntityStore);\n }\n\n protected async hasKeyInQueue(key: string) {\n return !!(await this.cache.get(`$$queue:${key}`));\n }\n\n protected async addKeyToQueue(key: string) {\n await this.cache.set(`$$queue:${key}`, true, {ttl: 120});\n }\n\n protected async deleteKeyFromQueue(key: string) {\n await this.cache.del(`$$queue:${key}`);\n }\n\n protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext) {\n const {headers, ttl} = cachedObject;\n const {request, response} = $ctx;\n\n const requestEtag = request.get(\"if-none-match\");\n\n if (requestEtag && headers.etag === requestEtag) {\n response.status(304).setHeaders(headers).body(undefined);\n\n return undefined;\n }\n\n const data = JSON.parse(cachedObject.data);\n\n $ctx.response\n .setHeaders({\n ...headers,\n \"x-cached\": \"true\",\n \"cache-control\": `max-age=${ttl}`\n })\n .body(data);\n\n return data;\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformCacheInterceptor.js","sourceRoot":"","sources":["../../../src/interceptors/PlatformCacheInterceptor.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAC,MAAM,YAAY,CAAC;AAC5D,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AC5C,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,WAAW,GAAG,EAAE,CAAC,CAAC;IACzC,CAAC;IAES,YAAY,CAAC,YAAkC,EAAE,IAAiB;QAC1E,MAAM,EAAC,OAAO,EAAE,GAAG,EAAC,GAAG,YAAY,CAAC;QACpC,MAAM,EAAC,OAAO,EAAE,QAAQ,EAAC,GAAG,IAAI,CAAC;QAEjC,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;QAEjD,IAAI,WAAW,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW,EAAE;YAC/C,QAAQ,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YAEzD,OAAO,SAAS,CAAC;SAClB;QAED,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAE3C,IAAI,CAAC,QAAQ;aACV,UAAU,CAAC;YACV,GAAG,OAAO;YACV,UAAU,EAAE,MAAM;YAClB,eAAe,EAAE,WAAW,GAAG,EAAE;SAClC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;QAEd,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAA;AA1KC;IADC,MAAM,EAAE;8BACQ,aAAa;uDAAC;AAG/B;IADC,MAAM,EAAE;8BACS,MAAM;wDAAC;AALd,wBAAwB;IADpC,WAAW,EAAE;GACD,wBAAwB,CA4KpC;SA5KY,wBAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {Logger} from \"@tsed/logger\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n @Inject()\n protected logger: Logger;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL < calculatedTTL - refreshThreshold) {\n await next();\n }\n\n await this.deleteKeyFromQueue(key);\n }\n }\n\n async cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {type, ttl, collectionType, refreshThreshold, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const set = (result: any) => {\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n const data = serialize(result, {type, collectionType});\n this.cache.setCachedObject(key, data, {args, ttl: calculatedTTL});\n };\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (!cachedObject) {\n const result = await next();\n\n set(result);\n\n return result;\n }\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n await set(result);\n }).catch((er) =>\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"cacheMethod\",\n error: er\n })\n );\n\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs};\n }\n\n protected isEndpoint({target, propertyKey}: InterceptorContext<any, PlatformCacheOptions>) {\n return Store.fromMethod(target, propertyKey).has(JsonEntityStore);\n }\n\n protected async hasKeyInQueue(key: string) {\n return !!(await this.cache.get(`$$queue:${key}`));\n }\n\n protected async addKeyToQueue(key: string) {\n await this.cache.set(`$$queue:${key}`, true, {ttl: 120});\n }\n\n protected async deleteKeyFromQueue(key: string) {\n await this.cache.del(`$$queue:${key}`);\n }\n\n protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext) {\n const {headers, ttl} = cachedObject;\n const {request, response} = $ctx;\n\n const requestEtag = request.get(\"if-none-match\");\n\n if (requestEtag && headers.etag === requestEtag) {\n response.status(304).setHeaders(headers).body(undefined);\n\n return undefined;\n }\n\n const data = JSON.parse(cachedObject.data);\n\n $ctx.response\n .setHeaders({\n ...headers,\n \"x-cached\": \"true\",\n \"cache-control\": `max-age=${ttl}`\n })\n .body(data);\n\n return data;\n }\n}\n"]}
@@ -1,5 +1,4 @@
1
- var _PlatformCache_cache;
2
- import { __classPrivateFieldGet, __classPrivateFieldSet, __decorate, __metadata } from "tslib";
1
+ import { __decorate, __metadata } from "tslib";
3
2
  import { isClass, isFunction } from "@tsed/core";
4
3
  import { Configuration, Inject, InjectorService, Module } from "@tsed/di";
5
4
  import { deserialize, serialize } from "@tsed/json-mapper";
@@ -11,17 +10,18 @@ const defaultKeyResolver = (args) => {
11
10
  * @platform
12
11
  */
13
12
  let PlatformCache = class PlatformCache {
14
- constructor() {
15
- _PlatformCache_cache.set(this, void 0);
16
- }
13
+ settings;
14
+ injector;
15
+ logger;
16
+ #cache;
17
17
  get cache() {
18
- return __classPrivateFieldGet(this, _PlatformCache_cache, "f");
18
+ return this.#cache;
19
19
  }
20
20
  async $onInit() {
21
21
  const settings = this.settings.get("cache");
22
22
  if (settings) {
23
- __classPrivateFieldSet(this, _PlatformCache_cache, await this.createCacheManager(settings), "f");
24
- await this.injector.emit("$onCreateCacheManager", __classPrivateFieldGet(this, _PlatformCache_cache, "f"));
23
+ this.#cache = await this.createCacheManager(settings);
24
+ await this.injector.emit("$onCreateCacheManager", this.#cache);
25
25
  }
26
26
  }
27
27
  disabled() {
@@ -43,19 +43,16 @@ let PlatformCache = class PlatformCache {
43
43
  }
44
44
  }
45
45
  wrap(key, fetch, options) {
46
- var _a;
47
46
  if (!this.cache) {
48
47
  return fetch();
49
48
  }
50
- return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.wrap(key, fetch, options);
49
+ return this.cache?.wrap(key, fetch, options);
51
50
  }
52
51
  async get(key, options = {}) {
53
- var _a;
54
- return deserialize((_a = this.cache) === null || _a === void 0 ? void 0 : _a.get(key), options);
52
+ return deserialize(this.cache?.get(key), options);
55
53
  }
56
54
  async set(key, value, options) {
57
- var _a;
58
- return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.set(key, value, options);
55
+ return this.cache?.set(key, value, options);
59
56
  }
60
57
  async getCachedObject(key) {
61
58
  try {
@@ -87,13 +84,11 @@ let PlatformCache = class PlatformCache {
87
84
  }
88
85
  }
89
86
  async del(key) {
90
- var _a;
91
- await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.del(key));
87
+ await this.cache?.del(key);
92
88
  }
93
89
  async reset() {
94
- var _a;
95
90
  // @ts-ignore
96
- await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.reset());
91
+ await this.cache?.reset();
97
92
  }
98
93
  async keys(...args) {
99
94
  if (this.cache && "store" in this.cache && this.cache.store.keys) {
@@ -115,7 +110,7 @@ let PlatformCache = class PlatformCache {
115
110
  const { caches, store = "memory", ttl, ...props } = settings;
116
111
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
117
112
  const { default: cacheManager } = await import("cache-manager");
118
- return (caches === null || caches === void 0 ? void 0 : caches.length)
113
+ return caches?.length
119
114
  ? cacheManager.multiCaching(caches, { ...props })
120
115
  : cacheManager.caching({
121
116
  ...props,
@@ -124,7 +119,6 @@ let PlatformCache = class PlatformCache {
124
119
  });
125
120
  }
126
121
  };
127
- _PlatformCache_cache = new WeakMap();
128
122
  __decorate([
129
123
  Configuration(),
130
124
  __metadata("design:type", Object)
@@ -1 +1 @@
1
- {"version":3,"file":"PlatformCache.js","sourceRoot":"","sources":["../../../src/services/PlatformCache.ts"],"names":[],"mappings":";;AAAA,OAAO,E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Aa,EAAE;;+CACkB;AAGlC;IADC,MAAM,EAAE;8BACW,eAAe;+CAAC;AAGpC;IADC,MAAM,EAAE;8BACS,MAAM;6CAAC;AARd,aAAa;IADzB,MAAM,EAAE;GACI,aAAa,CAgJzB;SAhJY,aAAa","sourcesContent":["import {isClass, isFunction} from \"@tsed/core\";\nimport {Configuration, Inject, InjectorService, Module} from \"@tsed/di\";\nimport {deserialize, JsonDeserializerOptions, serialize} from \"@tsed/json-mapper\";\nimport type {Cache, CachingConfig, MultiCache, TtlFunction} from \"cache-manager\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheSettings} from \"../interfaces/interfaces\";\nimport {Logger} from \"@tsed/logger\";\n\nconst defaultKeyResolver = (args: any[]) => {\n return args.map((arg: any) => (isClass(arg) ? JSON.stringify(serialize(arg)) : arg)).join(\":\");\n};\n\nexport type CacheManager = Cache | MultiCache;\n\n/**\n * @platform\n */\n@Module()\nexport class PlatformCache {\n @Configuration()\n protected settings: Configuration;\n\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected logger: Logger;\n\n #cache: CacheManager | undefined;\n\n get cache() {\n return this.#cache;\n }\n\n async $onInit() {\n const settings = this.settings.get<PlatformCacheSettings>(\"cache\");\n\n if (settings) {\n this.#cache = await this.createCacheManager(settings);\n\n await this.injector.emit(\"$onCreateCacheManager\", this.#cache);\n }\n }\n\n disabled(): boolean {\n return !this.settings.get<PlatformCacheSettings>(\"cache\");\n }\n\n defaultKeyResolver() {\n return this.settings.get<(args: any[], ctx?: any) => string>(\"cache.keyResolver\", defaultKeyResolver);\n }\n\n defaultTtl() {\n return this.settings.get<number | TtlFunction>(\"cache.ttl\");\n }\n\n calculateTTL(result?: any, currentTtl?: number | TtlFunction) {\n const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;\n\n return isFunction(ttl) ? ttl(result) : ttl;\n }\n\n async ttl(key: string) {\n if (this.cache && \"store\" in this.cache && this.cache.store.ttl) {\n return this.cache.store.ttl(key);\n }\n }\n\n wrap<T>(key: string, fetch: () => Promise<T>, options?: CachingConfig): Promise<T> {\n if (!this.cache) {\n return fetch();\n }\n\n return this.cache?.wrap<T>(key, fetch, options as any);\n }\n\n async get<T>(key: string, options: JsonDeserializerOptions = {}): Promise<T | undefined> {\n return deserialize(this.cache?.get<T>(key), options);\n }\n\n async set<T>(key: string, value: any, options?: CachingConfig): Promise<T | undefined> {\n return this.cache?.set<T>(key, value, options);\n }\n\n async getCachedObject(key: string) {\n try {\n return await this.get<PlatformCachedObject>(key);\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"getCachedObject\",\n error: er\n });\n }\n }\n\n async setCachedObject(key: string, data: any, opts: {ttl: number} & Record<string, any>) {\n try {\n await this.set<PlatformCachedObject>(\n key,\n {\n ...opts,\n data: JSON.stringify(data)\n },\n {\n ttl: opts.ttl\n }\n );\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"setCachedObject\",\n error: er\n });\n }\n }\n\n async del(key: string): Promise<void> {\n await this.cache?.del(key);\n }\n\n async reset(): Promise<void> {\n // @ts-ignore\n await this.cache?.reset();\n }\n\n async keys(...args: any[]): Promise<string[]> {\n if (this.cache && \"store\" in this.cache && this.cache.store.keys) {\n return this.cache.store.keys(...args);\n }\n\n // istanbul ignore next\n return [];\n }\n\n async getMatchingKeys(patterns: string): Promise<string[]> {\n const [keys, {default: micromatch}] = await Promise.all([this.keys(), import(\"micromatch\")]);\n\n return micromatch(keys, patterns);\n }\n\n async deleteMatchingKeys(patterns: string): Promise<string[]> {\n const keys = await this.getMatchingKeys(patterns);\n\n await Promise.all(keys.map((key: string) => this.del(key)));\n\n return keys;\n }\n\n protected async createCacheManager(settings: PlatformCacheSettings) {\n const {caches, store = \"memory\", ttl, ...props} = settings;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const {default: cacheManager} = await import(\"cache-manager\");\n\n return caches?.length\n ? cacheManager.multiCaching(caches, {...props})\n : cacheManager.caching({\n ...props,\n ttl,\n store: isFunction(store) ? await store() : store\n });\n }\n}\n"]}
1
+ {"version":3,"file":"PlatformCache.js","sourceRoot":"","sources":["../../../src/services/PlatformCache.ts"],"names":[],"mappings":";AAAA,OAAO,EAAC,OAAO,EAAE,UAAU,EAAC,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAC,aAAa,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAC,MAAM,UAAU,CAAC;AACxE,OAAO,EAAC,WAAW,EAA2B,SAAS,EAAC,MAAM,mBAAmB,CAAC;AAIlF,OAAO,EAAC,MAAM,EAAC,MAAM,cAAc,CAAC;AAEpC,MAAM,kBAAkB,GAAG,CAAC,IAAW,EAAE,EAAE;IACzC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,GAAQ,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACjG,CAAC,CAAC;AAIF;;GAEG;AAEH,IAAa,aAAa,GAA1B,MAAa,aAAa;IAEd,QAAQ,CAAgB;IAGxB,QAAQ,CAAkB;IAG1B,MAAM,CAAS;IAEzB,MAAM,CAA2B;IAEjC,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,OAAO;QACX,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAwB,OAAO,CAAC,CAAC;QAEnE,IAAI,QAAQ,EAAE;YACZ,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;YAEtD,MAAM,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,uBAAuB,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;SAChE;IACH,CAA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,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK;aACjD,CAAC,CAAC;IACT,CAAC;CACF,CAAA;AA9IC;IADC,aAAa,EAAE;;+CACkB;AAGlC;IADC,MAAM,EAAE;8BACW,eAAe;+CAAC;AAGpC;IADC,MAAM,EAAE;8BACS,MAAM;6CAAC;AARd,aAAa;IADzB,MAAM,EAAE;GACI,aAAa,CAgJzB;SAhJY,aAAa","sourcesContent":["import {isClass, isFunction} from \"@tsed/core\";\nimport {Configuration, Inject, InjectorService, Module} from \"@tsed/di\";\nimport {deserialize, JsonDeserializerOptions, serialize} from \"@tsed/json-mapper\";\nimport type {Cache, CachingConfig, MultiCache, TtlFunction} from \"cache-manager\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheSettings} from \"../interfaces/interfaces\";\nimport {Logger} from \"@tsed/logger\";\n\nconst defaultKeyResolver = (args: any[]) => {\n return args.map((arg: any) => (isClass(arg) ? JSON.stringify(serialize(arg)) : arg)).join(\":\");\n};\n\nexport type CacheManager = Cache | MultiCache;\n\n/**\n * @platform\n */\n@Module()\nexport class PlatformCache {\n @Configuration()\n protected settings: Configuration;\n\n @Inject()\n protected injector: InjectorService;\n\n @Inject()\n protected logger: Logger;\n\n #cache: CacheManager | undefined;\n\n get cache() {\n return this.#cache;\n }\n\n async $onInit() {\n const settings = this.settings.get<PlatformCacheSettings>(\"cache\");\n\n if (settings) {\n this.#cache = await this.createCacheManager(settings);\n\n await this.injector.emit(\"$onCreateCacheManager\", this.#cache);\n }\n }\n\n disabled(): boolean {\n return !this.settings.get<PlatformCacheSettings>(\"cache\");\n }\n\n defaultKeyResolver() {\n return this.settings.get<(args: any[], ctx?: any) => string>(\"cache.keyResolver\", defaultKeyResolver);\n }\n\n defaultTtl() {\n return this.settings.get<number | TtlFunction>(\"cache.ttl\");\n }\n\n calculateTTL(result?: any, currentTtl?: number | TtlFunction) {\n const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;\n\n return isFunction(ttl) ? ttl(result) : ttl;\n }\n\n async ttl(key: string) {\n if (this.cache && \"store\" in this.cache && this.cache.store.ttl) {\n return this.cache.store.ttl(key);\n }\n }\n\n wrap<T>(key: string, fetch: () => Promise<T>, options?: CachingConfig): Promise<T> {\n if (!this.cache) {\n return fetch();\n }\n\n return this.cache?.wrap<T>(key, fetch, options as any);\n }\n\n async get<T>(key: string, options: JsonDeserializerOptions = {}): Promise<T | undefined> {\n return deserialize(this.cache?.get<T>(key), options);\n }\n\n async set<T>(key: string, value: any, options?: CachingConfig): Promise<T | undefined> {\n return this.cache?.set<T>(key, value, options);\n }\n\n async getCachedObject(key: string) {\n try {\n return await this.get<PlatformCachedObject>(key);\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"getCachedObject\",\n error: er\n });\n }\n }\n\n async setCachedObject(key: string, data: any, opts: {ttl: number} & Record<string, any>) {\n try {\n await this.set<PlatformCachedObject>(\n key,\n {\n ...opts,\n data: JSON.stringify(data)\n },\n {\n ttl: opts.ttl\n }\n );\n } catch (er) {\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"setCachedObject\",\n error: er\n });\n }\n }\n\n async del(key: string): Promise<void> {\n await this.cache?.del(key);\n }\n\n async reset(): Promise<void> {\n // @ts-ignore\n await this.cache?.reset();\n }\n\n async keys(...args: any[]): Promise<string[]> {\n if (this.cache && \"store\" in this.cache && this.cache.store.keys) {\n return this.cache.store.keys(...args);\n }\n\n // istanbul ignore next\n return [];\n }\n\n async getMatchingKeys(patterns: string): Promise<string[]> {\n const [keys, {default: micromatch}] = await Promise.all([this.keys(), import(\"micromatch\")]);\n\n return micromatch(keys, patterns);\n }\n\n async deleteMatchingKeys(patterns: string): Promise<string[]> {\n const keys = await this.getMatchingKeys(patterns);\n\n await Promise.all(keys.map((key: string) => this.del(key)));\n\n return keys;\n }\n\n protected async createCacheManager(settings: PlatformCacheSettings) {\n const {caches, store = \"memory\", ttl, ...props} = settings;\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const {default: cacheManager} = await import(\"cache-manager\");\n\n return caches?.length\n ? cacheManager.multiCaching(caches, {...props})\n : cacheManager.caching({\n ...props,\n ttl,\n store: isFunction(store) ? await store() : store\n });\n }\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import { BaseContext, InterceptorContext, InterceptorMethods, InterceptorNext } from "@tsed/di";
2
+ import { Logger } from "@tsed/logger";
2
3
  import { PlatformCachedObject } from "../interfaces/PlatformCachedObject";
3
4
  import { PlatformCacheOptions } from "../interfaces/PlatformCacheOptions";
4
5
  import { PlatformCache } from "../services/PlatformCache";
@@ -7,6 +8,7 @@ import { PlatformCache } from "../services/PlatformCache";
7
8
  */
8
9
  export declare class PlatformCacheInterceptor implements InterceptorMethods {
9
10
  protected cache: PlatformCache;
11
+ protected logger: Logger;
10
12
  intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext): Promise<any>;
11
13
  canRefreshInBackground(key: string, { refreshThreshold, ttl }: {
12
14
  refreshThreshold?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsed/platform-cache",
3
- "version": "7.0.0-beta.7",
3
+ "version": "7.0.0-rc.1",
4
4
  "description": "Platform cache module for Ts.ED Framework",
5
5
  "private": false,
6
6
  "source": "./src/index.ts",
@@ -21,23 +21,23 @@
21
21
  "barrels": "yarn barrelsby --delete -d ./src -e \"\\.spec\\.ts\" -e \"__mock__\" -e \".benchmark.ts\""
22
22
  },
23
23
  "dependencies": {
24
- "@types/cache-manager": "^3.4.3",
25
- "cache-manager": "^3.6.0",
24
+ "@types/cache-manager": "^4.0.1",
25
+ "cache-manager": "^4.1.0",
26
26
  "micromatch": "4.0.5",
27
- "tslib": "2.3.1"
27
+ "tslib": "2.4.0"
28
28
  },
29
29
  "devDependencies": {
30
- "@tsed/core": "7.0.0-beta.7",
31
- "@tsed/di": "7.0.0-beta.7",
32
- "@tsed/json-mapper": "7.0.0-beta.7",
33
- "@tsed/schema": "7.0.0-beta.7",
30
+ "@tsed/core": "7.0.0-rc.1",
31
+ "@tsed/di": "7.0.0-rc.1",
32
+ "@tsed/json-mapper": "7.0.0-rc.1",
33
+ "@tsed/schema": "7.0.0-rc.1",
34
34
  "@types/micromatch": "^4.0.1"
35
35
  },
36
36
  "peerDependencies": {
37
- "@tsed/core": "^7.0.0-beta.7",
38
- "@tsed/di": "^7.0.0-beta.7",
39
- "@tsed/json-mapper": "^7.0.0-beta.7",
40
- "@tsed/schema": "^7.0.0-beta.7"
37
+ "@tsed/core": "^7.0.0-rc.1",
38
+ "@tsed/di": "^7.0.0-rc.1",
39
+ "@tsed/json-mapper": "^7.0.0-rc.1",
40
+ "@tsed/schema": "^7.0.0-rc.1"
41
41
  },
42
42
  "peerDependenciesMeta": {
43
43
  "@tsed/core": {
@@ -57,7 +57,10 @@
57
57
  "bugs": {
58
58
  "url": "https://github.com/tsedio/tsed/issues"
59
59
  },
60
- "homepage": "https://github.com/tsedio/tsed/tree/production/packages/platform/platform-cache",
60
+ "homepage": "https://github.com/tsedio/tsed/tree/rc/packages/platform/platform-cache",
61
61
  "author": "Romain Lenzotti",
62
- "license": "MIT"
62
+ "license": "MIT",
63
+ "publishConfig": {
64
+ "tag": "rc"
65
+ }
63
66
  }
package/readme.md CHANGED
@@ -11,7 +11,8 @@
11
11
  [![npm version](https://badge.fury.io/js/%40tsed%2Fcommon.svg)](https://badge.fury.io/js/%40tsed%2Fcommon)
12
12
  [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
13
13
  [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
14
- [![backers](https://opencollective.com/tsed/tiers/badge.svg)](https://opencollective.com/tsed)
14
+ [![github](https://img.shields.io/static/v1?label=Github%20sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/romakita)
15
+ [![opencollective](https://img.shields.io/static/v1?label=OpenCollective%20sponsor&message=%E2%9D%A4&logo=OpenCollective&color=%23fe8e86)](https://opencollective.com/tsed)
15
16
 
16
17
  </div>
17
18
 
@@ -55,7 +56,7 @@ Support this project by becoming a sponsor. Your logo will show up here with a l
55
56
 
56
57
  The MIT License (MIT)
57
58
 
58
- Copyright (c) 2016 - 2018 Romain Lenzotti
59
+ Copyright (c) 2016 - 2022 Romain Lenzotti
59
60
 
60
61
  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
61
62