@tsed/platform-cache 6.87.2 → 6.90.0

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.
Files changed (49) hide show
  1. package/lib/{decorators → cjs/decorators}/useCache.d.ts +0 -0
  2. package/lib/cjs/decorators/useCache.js +11 -0
  3. package/lib/cjs/decorators/useCache.js.map +1 -0
  4. package/lib/{index.d.ts → cjs/index.d.ts} +0 -2
  5. package/lib/cjs/index.js +7 -0
  6. package/lib/cjs/index.js.map +1 -0
  7. package/lib/{interceptors → cjs/interceptors}/PlatformCacheInterceptor.d.ts +0 -0
  8. package/lib/cjs/interceptors/PlatformCacheInterceptor.js +134 -0
  9. package/lib/cjs/interceptors/PlatformCacheInterceptor.js.map +1 -0
  10. package/lib/{interfaces → cjs/interfaces}/PlatformCacheOptions.d.ts +0 -0
  11. package/lib/cjs/interfaces/PlatformCacheOptions.js +3 -0
  12. package/lib/cjs/interfaces/PlatformCacheOptions.js.map +1 -0
  13. package/lib/{interfaces → cjs/interfaces}/PlatformCachedObject.d.ts +0 -0
  14. package/lib/cjs/interfaces/PlatformCachedObject.js +3 -0
  15. package/lib/cjs/interfaces/PlatformCachedObject.js.map +1 -0
  16. package/lib/{interfaces → cjs/interfaces}/index.d.ts +0 -0
  17. package/lib/cjs/interfaces/index.js +5 -0
  18. package/lib/cjs/interfaces/index.js.map +1 -0
  19. package/lib/{services → cjs/services}/PlatformCache.d.ts +0 -0
  20. package/lib/cjs/services/PlatformCache.js +96 -0
  21. package/lib/cjs/services/PlatformCache.js.map +1 -0
  22. package/lib/esm/decorators/useCache.js +7 -0
  23. package/lib/esm/decorators/useCache.js.map +1 -0
  24. package/lib/esm/index.js +4 -0
  25. package/lib/esm/index.js.map +1 -0
  26. package/lib/esm/interceptors/PlatformCacheInterceptor.js +131 -0
  27. package/lib/esm/interceptors/PlatformCacheInterceptor.js.map +1 -0
  28. package/lib/esm/interfaces/PlatformCacheOptions.js +2 -0
  29. package/lib/esm/interfaces/PlatformCacheOptions.js.map +1 -0
  30. package/lib/esm/interfaces/PlatformCachedObject.js +2 -0
  31. package/lib/esm/interfaces/PlatformCachedObject.js.map +1 -0
  32. package/lib/esm/interfaces/index.js +2 -0
  33. package/lib/esm/interfaces/index.js.map +1 -0
  34. package/lib/esm/services/PlatformCache.js +93 -0
  35. package/lib/esm/services/PlatformCache.js.map +1 -0
  36. package/lib/types/decorators/useCache.d.ts +2 -0
  37. package/lib/types/index.d.ts +3 -0
  38. package/lib/types/interceptors/PlatformCacheInterceptor.d.ts +23 -0
  39. package/lib/types/interfaces/PlatformCacheOptions.d.ts +7 -0
  40. package/lib/types/interfaces/PlatformCachedObject.d.ts +7 -0
  41. package/lib/types/interfaces/index.d.ts +23 -0
  42. package/lib/types/services/PlatformCache.d.ts +28 -0
  43. package/package.json +20 -16
  44. package/tsconfig.compile.esm.json +23 -0
  45. package/lib/PlatformCacheModule.d.ts +0 -5
  46. package/lib/index.js +0 -372
  47. package/lib/index.js.map +0 -1
  48. package/lib/index.modern.js +0 -353
  49. package/lib/index.modern.js.map +0 -1
@@ -0,0 +1,93 @@
1
+ import { __decorate, __metadata } from "tslib";
2
+ import { isClass, isFunction } from "@tsed/core";
3
+ import { Configuration, Module } from "@tsed/di";
4
+ import { deserialize, serialize } from "@tsed/json-mapper";
5
+ const defaultKeyResolver = (args) => {
6
+ return args.map((arg) => (isClass(arg) ? JSON.stringify(serialize(arg)) : arg)).join(":");
7
+ };
8
+ /**
9
+ * @platform
10
+ */
11
+ let PlatformCache = class PlatformCache {
12
+ disabled() {
13
+ return !this.settings.get("cache");
14
+ }
15
+ async $onInit() {
16
+ const settings = this.settings.get("cache");
17
+ if (settings) {
18
+ this.cache = await this.createCacheManager(settings);
19
+ }
20
+ }
21
+ defaultKeyResolver() {
22
+ return this.settings.get("cache.keyResolver", defaultKeyResolver);
23
+ }
24
+ defaultTtl() {
25
+ return this.settings.get("cache.ttl");
26
+ }
27
+ ttl(result, currentTtl) {
28
+ const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;
29
+ return isFunction(ttl) ? ttl(result) : ttl;
30
+ }
31
+ wrap(key, fetch, options) {
32
+ var _a;
33
+ if (!this.cache) {
34
+ return fetch();
35
+ }
36
+ return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.wrap(key, fetch, options);
37
+ }
38
+ async get(key, options = {}) {
39
+ var _a;
40
+ return deserialize((_a = this.cache) === null || _a === void 0 ? void 0 : _a.get(key), options);
41
+ }
42
+ async set(key, value, options) {
43
+ var _a;
44
+ return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.set(key, value, options);
45
+ }
46
+ async del(key) {
47
+ var _a;
48
+ await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.del(key));
49
+ }
50
+ async reset() {
51
+ var _a;
52
+ // @ts-ignore
53
+ await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.reset());
54
+ }
55
+ async keys() {
56
+ var _a;
57
+ if ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.keys) {
58
+ return this.cache.keys();
59
+ }
60
+ // istanbul ignore next
61
+ return [];
62
+ }
63
+ async getMatchingKeys(patterns) {
64
+ const [keys, { default: micromatch }] = await Promise.all([this.keys(), import("micromatch")]);
65
+ return micromatch(keys, patterns);
66
+ }
67
+ async deleteMatchingKeys(patterns) {
68
+ const keys = await this.getMatchingKeys(patterns);
69
+ await Promise.all(keys.map((key) => this.del(key)));
70
+ return keys;
71
+ }
72
+ async createCacheManager(settings) {
73
+ const { caches, store = "memory", ttl, ...props } = settings;
74
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
75
+ const { default: cacheManager } = await import("cache-manager");
76
+ return (caches === null || caches === void 0 ? void 0 : caches.length)
77
+ ? cacheManager.multiCaching(caches, { ...props })
78
+ : cacheManager.caching({
79
+ ...props,
80
+ ttl,
81
+ store: isFunction(store) ? await store() : store
82
+ });
83
+ }
84
+ };
85
+ __decorate([
86
+ Configuration(),
87
+ __metadata("design:type", Object)
88
+ ], PlatformCache.prototype, "settings", void 0);
89
+ PlatformCache = __decorate([
90
+ Module()
91
+ ], PlatformCache);
92
+ export { PlatformCache };
93
+ //# sourceMappingURL=PlatformCache.js.map
@@ -0,0 +1 @@
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,EAAC,MAAM,UAAU,CAAC;AAC/C,OAAO,EAAC,WAAW,EAA2B,SAAS,EAAC,MAAM,mBAAmB,CAAC;AAIlF,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;AAMF;;GAEG;AAEH,IAAa,aAAa,GAA1B,MAAa,aAAa;IAMxB,QAAQ;QACN,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAwB,OAAO,CAAC,CAAC;IAC5D,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,KAAK,GAAG,MAAM,IAAI,CAAC,kBAAkB,CAAC,QAAQ,CAAC,CAAC;SACtD;IACH,CAAC;IAED,kBAAkB;QAChB,OAAO,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAqC,mBAAmB,EAAE,kBAAkB,CAAC,CAAC;IACxG,CAAC;IAED,UAAU;QACR,OAAO,IAAI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,MAAM,KAAK,EAAE,CAAC,CAAC,CAAC,KAAK;aACjD,CAAC,CAAC;IACT,CAAC;CACF,CAAA;AA1FC;IADC,aAAa,EAAE;;+CACQ;AAFb,aAAa;IADzB,MAAM,EAAE;GACI,aAAa,CA4FzB;SA5FY,aAAa","sourcesContent":["import {isClass, isFunction} from \"@tsed/core\";\nimport {Configuration, Module} from \"@tsed/di\";\nimport {deserialize, JsonDeserializerOptions, serialize} from \"@tsed/json-mapper\";\nimport type {Cache, CachingConfig, MultiCache, TtlFunction} from \"cache-manager\";\nimport {PlatformCacheSettings} from \"../interfaces\";\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 keys?(): Promise<string[]>;\n};\n\n/**\n * @platform\n */\n@Module()\nexport class PlatformCache {\n @Configuration()\n settings: Configuration;\n\n cache: CacheManager | undefined;\n\n disabled(): boolean {\n return !this.settings.get<PlatformCacheSettings>(\"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 }\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 ttl(result?: any, currentTtl?: number | TtlFunction) {\n const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;\n\n return isFunction(ttl) ? ttl(result) : ttl;\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 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(): Promise<string[]> {\n if (this.cache?.keys) {\n return this.cache.keys();\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"]}
@@ -0,0 +1,2 @@
1
+ import { PlatformCacheOptions } from "../interfaces/PlatformCacheOptions";
2
+ export declare function UseCache(options?: PlatformCacheOptions): any;
@@ -0,0 +1,3 @@
1
+ export * from "./interfaces";
2
+ export * from "./services/PlatformCache";
3
+ export * from "./decorators/useCache";
@@ -0,0 +1,23 @@
1
+ import { BaseContext, InterceptorContext, InterceptorMethods, InterceptorNext } from "@tsed/di";
2
+ import { PlatformCachedObject } from "../interfaces/PlatformCachedObject";
3
+ import { PlatformCacheOptions } from "../interfaces/PlatformCacheOptions";
4
+ import { PlatformCache } from "../services/PlatformCache";
5
+ /**
6
+ * @platform
7
+ */
8
+ export declare class PlatformCacheInterceptor implements InterceptorMethods {
9
+ protected cache: PlatformCache;
10
+ intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext): Promise<any>;
11
+ protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>): any;
12
+ protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>): {
13
+ ttl: number | import("cache-manager").TtlFunction | undefined;
14
+ type: any;
15
+ args: any;
16
+ collectionType: any;
17
+ keyArgs: string;
18
+ };
19
+ protected isEndpoint({ target, propertyKey }: InterceptorContext<any, PlatformCacheOptions>): boolean;
20
+ protected cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext): Promise<any>;
21
+ protected cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext): Promise<any>;
22
+ protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext): any;
23
+ }
@@ -0,0 +1,7 @@
1
+ import { MetadataTypes } from "@tsed/core";
2
+ import { BaseContext } from "@tsed/di";
3
+ import type { TtlFunction } from "cache-manager";
4
+ export interface PlatformCacheOptions extends MetadataTypes {
5
+ ttl?: number | TtlFunction;
6
+ key?: string | ((args: any[], ctx?: BaseContext) => string);
7
+ }
@@ -0,0 +1,7 @@
1
+ export interface PlatformCachedObject {
2
+ ttl: number;
3
+ args: any[];
4
+ data: any;
5
+ expires: number;
6
+ headers: Record<string, number | string | string[]>;
7
+ }
@@ -0,0 +1,23 @@
1
+ import type { BaseContext } from "@tsed/di";
2
+ import type { Cache, CacheOptions, CachingConfig, Store } from "cache-manager";
3
+ export * from "./PlatformCachedObject";
4
+ export interface PlatformCacheSettings extends CacheOptions, CachingConfig {
5
+ caches?: Cache[];
6
+ store?: "memory" | "none" | Store | {
7
+ create(...args: any[]): Store;
8
+ } | (() => any);
9
+ max?: number;
10
+ keyResolver?: (args: any[], ctx: BaseContext) => string;
11
+ /**
12
+ * You may pass in any other arguments these will be passed on to the `create` method of your store,
13
+ * otherwise they will be ignored.
14
+ */
15
+ [key: string]: any;
16
+ }
17
+ declare global {
18
+ namespace TsED {
19
+ interface Configuration {
20
+ cache?: PlatformCacheSettings | false;
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,28 @@
1
+ import { Configuration } from "@tsed/di";
2
+ import { JsonDeserializerOptions } from "@tsed/json-mapper";
3
+ import type { Cache, CachingConfig, MultiCache, TtlFunction } from "cache-manager";
4
+ import { PlatformCacheSettings } from "../interfaces";
5
+ export declare type CacheManager = (Cache | MultiCache) & {
6
+ keys?(): Promise<string[]>;
7
+ };
8
+ /**
9
+ * @platform
10
+ */
11
+ export declare class PlatformCache {
12
+ settings: Configuration;
13
+ cache: CacheManager | undefined;
14
+ disabled(): boolean;
15
+ $onInit(): Promise<void>;
16
+ defaultKeyResolver(): (args: any[], ctx?: any) => string;
17
+ defaultTtl(): number | TtlFunction;
18
+ ttl(result?: any, currentTtl?: number | TtlFunction): number;
19
+ wrap<T>(key: string, fetch: () => Promise<T>, options?: CachingConfig): Promise<T>;
20
+ get<T>(key: string, options?: JsonDeserializerOptions): Promise<T | undefined>;
21
+ set<T>(key: string, value: any, options?: CachingConfig): Promise<T | undefined>;
22
+ del(key: string): Promise<void>;
23
+ reset(): Promise<void>;
24
+ keys(): Promise<string[]>;
25
+ getMatchingKeys(patterns: string): Promise<string[]>;
26
+ deleteMatchingKeys(patterns: string): Promise<string[]>;
27
+ protected createCacheManager(settings: PlatformCacheSettings): Promise<MultiCache>;
28
+ }
package/package.json CHANGED
@@ -1,17 +1,21 @@
1
1
  {
2
2
  "name": "@tsed/platform-cache",
3
- "version": "6.87.2",
3
+ "version": "6.90.0",
4
4
  "description": "Platform cache module for Ts.ED Framework",
5
5
  "private": false,
6
6
  "source": "./src/index.ts",
7
- "main": "./lib/index.js",
8
- "typings": "./lib/index.d.ts",
7
+ "main": "./lib/cjs/index.js",
8
+ "typings": "./lib/types/index.d.ts",
9
9
  "exports": {
10
- "require": "./lib/index.js",
11
- "default": "./lib/index.modern.js"
10
+ "types": "./lib/types/index.d.ts",
11
+ "import": "./lib/esm/index.js",
12
+ "require": "./lib/cjs/index.js",
13
+ "default": "./lib/esm/index.js"
12
14
  },
13
15
  "scripts": {
14
- "build": "microbundle --target node --no-compress --format modern,cjs --tsconfig ./tsconfig.compile.json"
16
+ "build": "yarn run build:esm && yarn run build:cjs",
17
+ "build:cjs": "tsc --build tsconfig.compile.json",
18
+ "build:esm": "tsc --build tsconfig.compile.esm.json"
15
19
  },
16
20
  "dependencies": {
17
21
  "@types/cache-manager": "^3.4.2",
@@ -20,20 +24,20 @@
20
24
  "tslib": "2.2.0"
21
25
  },
22
26
  "devDependencies": {
23
- "@tsed/core": "6.87.2",
24
- "@tsed/di": "6.87.2",
25
- "@tsed/exceptions": "6.87.2",
26
- "@tsed/json-mapper": "6.87.2",
27
- "@tsed/schema": "6.87.2",
27
+ "@tsed/core": "6.90.0",
28
+ "@tsed/di": "6.90.0",
29
+ "@tsed/exceptions": "6.90.0",
30
+ "@tsed/json-mapper": "6.90.0",
31
+ "@tsed/schema": "6.90.0",
28
32
  "@types/cache-manager": "^3.4.2",
29
33
  "@types/micromatch": "^4.0.1"
30
34
  },
31
35
  "peerDependencies": {
32
- "@tsed/core": "^6.87.2",
33
- "@tsed/di": "^6.87.2",
34
- "@tsed/exceptions": "^6.87.2",
35
- "@tsed/json-mapper": "^6.87.2",
36
- "@tsed/schema": "^6.87.2"
36
+ "@tsed/core": "^6.90.0",
37
+ "@tsed/di": "^6.90.0",
38
+ "@tsed/exceptions": "^6.90.0",
39
+ "@tsed/json-mapper": "^6.90.0",
40
+ "@tsed/schema": "^6.90.0"
37
41
  },
38
42
  "repository": "https://github.com/tsedio/tsed",
39
43
  "bugs": {
@@ -0,0 +1,23 @@
1
+ {
2
+ "extends": "./tsconfig.compile.json",
3
+ "compilerOptions": {
4
+ "baseUrl": ".",
5
+ "module": "ES2020",
6
+ "rootDir": "src",
7
+ "outDir": "./lib/esm",
8
+ "declaration": true,
9
+ "declarationDir": "./lib/types"
10
+ },
11
+ "exclude": [
12
+ "node_modules",
13
+ "test",
14
+ "lib",
15
+ "benchmark",
16
+ "coverage",
17
+ "spec",
18
+ "**/*.benchmark.ts",
19
+ "**/*.spec.ts",
20
+ "keys",
21
+ "jest.config.js"
22
+ ]
23
+ }
@@ -1,5 +0,0 @@
1
- /**
2
- * @ignore
3
- */
4
- export declare class PlatformCacheModule {
5
- }
package/lib/index.js DELETED
@@ -1,372 +0,0 @@
1
- var tslib = require('tslib');
2
- var core = require('@tsed/core');
3
- var di = require('@tsed/di');
4
- var jsonMapper = require('@tsed/json-mapper');
5
- var schema = require('@tsed/schema');
6
- var http = require('http');
7
-
8
- function _interopNamespace(e) {
9
- if (e && e.__esModule) return e;
10
- var n = Object.create(null);
11
- if (e) {
12
- Object.keys(e).forEach(function (k) {
13
- if (k !== 'default') {
14
- var d = Object.getOwnPropertyDescriptor(e, k);
15
- Object.defineProperty(n, k, d.get ? d : {
16
- enumerable: true,
17
- get: function () {
18
- return e[k];
19
- }
20
- });
21
- }
22
- });
23
- }
24
- n['default'] = e;
25
- return n;
26
- }
27
-
28
- function _extends() {
29
- _extends = Object.assign || function (target) {
30
- for (var i = 1; i < arguments.length; i++) {
31
- var source = arguments[i];
32
-
33
- for (var key in source) {
34
- if (Object.prototype.hasOwnProperty.call(source, key)) {
35
- target[key] = source[key];
36
- }
37
- }
38
- }
39
-
40
- return target;
41
- };
42
-
43
- return _extends.apply(this, arguments);
44
- }
45
-
46
- function _objectWithoutPropertiesLoose(source, excluded) {
47
- if (source == null) return {};
48
- var target = {};
49
- var sourceKeys = Object.keys(source);
50
- var key, i;
51
-
52
- for (i = 0; i < sourceKeys.length; i++) {
53
- key = sourceKeys[i];
54
- if (excluded.indexOf(key) >= 0) continue;
55
- target[key] = source[key];
56
- }
57
-
58
- return target;
59
- }
60
-
61
- const _excluded = ["caches", "store", "ttl"];
62
-
63
- const defaultKeyResolver = args => {
64
- return args.map(arg => core.isClass(arg) ? JSON.stringify(jsonMapper.serialize(arg)) : arg).join(":");
65
- };
66
- /**
67
- * @platform
68
- */
69
-
70
-
71
- exports.PlatformCache = class PlatformCache {
72
- disabled() {
73
- return !this.settings.get("cache");
74
- }
75
-
76
- async $onInit() {
77
- const settings = this.settings.get("cache");
78
-
79
- if (settings) {
80
- this.cache = await this.createCacheManager(settings);
81
- }
82
- }
83
-
84
- defaultKeyResolver() {
85
- return this.settings.get("cache.keyResolver", defaultKeyResolver);
86
- }
87
-
88
- defaultTtl() {
89
- return this.settings.get("cache.ttl");
90
- }
91
-
92
- ttl(result, currentTtl) {
93
- const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;
94
- return core.isFunction(ttl) ? ttl(result) : ttl;
95
- }
96
-
97
- wrap(key, fetch, options) {
98
- var _this$cache;
99
-
100
- if (!this.cache) {
101
- return fetch();
102
- }
103
-
104
- return (_this$cache = this.cache) == null ? void 0 : _this$cache.wrap(key, fetch, options);
105
- }
106
-
107
- async get(key, options = {}) {
108
- var _this$cache2;
109
-
110
- return jsonMapper.deserialize((_this$cache2 = this.cache) == null ? void 0 : _this$cache2.get(key), options);
111
- }
112
-
113
- async set(key, value, options) {
114
- var _this$cache3;
115
-
116
- return (_this$cache3 = this.cache) == null ? void 0 : _this$cache3.set(key, value, options);
117
- }
118
-
119
- async del(key) {
120
- var _this$cache4;
121
-
122
- await ((_this$cache4 = this.cache) == null ? void 0 : _this$cache4.del(key));
123
- }
124
-
125
- async reset() {
126
- var _this$cache5;
127
-
128
- // @ts-ignore
129
- await ((_this$cache5 = this.cache) == null ? void 0 : _this$cache5.reset());
130
- }
131
-
132
- async keys() {
133
- var _this$cache6;
134
-
135
- if ((_this$cache6 = this.cache) != null && _this$cache6.keys) {
136
- return this.cache.keys();
137
- } // istanbul ignore next
138
-
139
-
140
- return [];
141
- }
142
-
143
- async getMatchingKeys(patterns) {
144
- const [keys, {
145
- default: micromatch
146
- }] = await Promise.all([this.keys(), Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('micromatch')); })]);
147
- return micromatch(keys, patterns);
148
- }
149
-
150
- async deleteMatchingKeys(patterns) {
151
- const keys = await this.getMatchingKeys(patterns);
152
- await Promise.all(keys.map(key => this.del(key)));
153
- return keys;
154
- }
155
-
156
- async createCacheManager(settings) {
157
- const {
158
- caches,
159
- store = "memory",
160
- ttl
161
- } = settings,
162
- props = _objectWithoutPropertiesLoose(settings, _excluded); // eslint-disable-next-line @typescript-eslint/no-unused-vars
163
-
164
-
165
- const {
166
- default: cacheManager
167
- } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('cache-manager')); });
168
- return caches != null && caches.length ? cacheManager.multiCaching(caches, _extends({}, props)) : cacheManager.caching(_extends({}, props, {
169
- ttl,
170
- store: core.isFunction(store) ? await store() : store
171
- }));
172
- }
173
-
174
- };
175
-
176
- tslib.__decorate([di.Configuration(), tslib.__metadata("design:type", Object)], exports.PlatformCache.prototype, "settings", void 0);
177
-
178
- exports.PlatformCache = tslib.__decorate([di.Injectable()], exports.PlatformCache);
179
-
180
- const cleanHeaders = headers => {
181
- return Object.entries(headers).filter(([key]) => !["content-length", "x-request-id", "cache-control"].includes(key)).reduce((headers, [key, value]) => {
182
- return _extends({}, headers, {
183
- [key]: value
184
- });
185
- }, {});
186
- };
187
- /**
188
- * @platform
189
- */
190
-
191
-
192
- let PlatformCacheInterceptor = class PlatformCacheInterceptor {
193
- async intercept(context, next) {
194
- if (this.cache.disabled()) {
195
- return next();
196
- }
197
-
198
- if (!this.isEndpoint(context)) {
199
- return this.cacheMethod(context, next);
200
- }
201
-
202
- return this.cacheResponse(context, next);
203
- }
204
-
205
- getArgs(context) {
206
- return context.args.reduce((args, arg) => {
207
- if (arg instanceof di.DIContext || arg instanceof http.IncomingMessage || arg instanceof http.ServerResponse) {
208
- return args;
209
- }
210
-
211
- if (core.isClass(arg)) {
212
- return args.concat(jsonMapper.serialize(arg));
213
- }
214
-
215
- return args.concat(arg);
216
- }, []);
217
- }
218
-
219
- getOptions(context) {
220
- const {
221
- ttl,
222
- type,
223
- collectionType,
224
- key: k = this.cache.defaultKeyResolver()
225
- } = context.options || {};
226
- const args = this.getArgs(context);
227
- const keyArgs = core.isString(k) ? k : k(args);
228
- return {
229
- ttl,
230
- type,
231
- args,
232
- collectionType,
233
- keyArgs
234
- };
235
- }
236
-
237
- isEndpoint({
238
- target,
239
- propertyKey
240
- }) {
241
- return core.Store.fromMethod(target, propertyKey).has(schema.JsonEntityStore);
242
- }
243
-
244
- async cacheMethod(context, next) {
245
- const {
246
- ttl,
247
- type,
248
- collectionType,
249
- keyArgs,
250
- args
251
- } = this.getOptions(context);
252
- const key = [core.nameOf(context.target), context.propertyKey, keyArgs].join(":");
253
- const cachedObject = await this.cache.get(key);
254
-
255
- if (cachedObject) {
256
- const {
257
- data
258
- } = cachedObject;
259
- return jsonMapper.deserialize(JSON.parse(data), {
260
- collectionType,
261
- type
262
- });
263
- }
264
-
265
- const result = await next();
266
- const calculatedTtl = this.cache.ttl(result, ttl);
267
- await this.cache.set(key, {
268
- ttl: calculatedTtl,
269
- args,
270
- data: JSON.stringify(jsonMapper.serialize(result, {
271
- type,
272
- collectionType
273
- }))
274
- }, {
275
- ttl: calculatedTtl
276
- });
277
- return result;
278
- }
279
-
280
- async cacheResponse(context, next) {
281
- const $ctx = context.args[context.args.length - 1];
282
- const {
283
- request,
284
- response
285
- } = $ctx;
286
-
287
- if (request.method !== "GET") {
288
- return next();
289
- }
290
-
291
- const {
292
- ttl,
293
- args,
294
- keyArgs
295
- } = this.getOptions(context);
296
- const key = [request.method, request.url, keyArgs].join(":");
297
- const cachedObject = await this.cache.get(key);
298
-
299
- if (cachedObject && !(response.get("cache-control") === "no-cache")) {
300
- return this.sendResponse(cachedObject, $ctx);
301
- }
302
-
303
- const result = await next();
304
- const calculatedTtl = this.cache.ttl(result, ttl);
305
- const expires = calculatedTtl + Date.now() / 1000;
306
- $ctx.response.setHeaders({
307
- "cache-control": `max-age=${calculatedTtl}`
308
- }); // cache final response with his headers and body
309
-
310
- response.onEnd(async () => {
311
- const data = JSON.stringify(response.getBody());
312
- const headers = cleanHeaders(response.getHeaders());
313
- await this.cache.set(key, {
314
- ttl: calculatedTtl,
315
- args,
316
- data,
317
- expires,
318
- headers
319
- }, {
320
- ttl: calculatedTtl
321
- });
322
- });
323
- return result;
324
- }
325
-
326
- sendResponse(cachedObject, $ctx) {
327
- const {
328
- headers,
329
- ttl
330
- } = cachedObject;
331
- const {
332
- request,
333
- response
334
- } = $ctx;
335
- const requestEtag = request.get("if-none-match");
336
-
337
- if (requestEtag && headers.etag === requestEtag) {
338
- response.status(304).setHeaders(headers).body(undefined);
339
- return undefined;
340
- }
341
-
342
- const data = JSON.parse(cachedObject.data);
343
- $ctx.response.setHeaders(_extends({}, headers, {
344
- "x-cached": "true",
345
- "cache-control": `max-age=${ttl}`
346
- })).body(data);
347
- return data;
348
- }
349
-
350
- };
351
-
352
- tslib.__decorate([di.Inject(), tslib.__metadata("design:type", exports.PlatformCache)], PlatformCacheInterceptor.prototype, "cache", void 0);
353
-
354
- PlatformCacheInterceptor = tslib.__decorate([di.Interceptor()], PlatformCacheInterceptor);
355
-
356
- function UseCache(options = {}) {
357
- return core.useDecorators(di.Intercept(PlatformCacheInterceptor, options));
358
- }
359
-
360
- /**
361
- * @ignore
362
- */
363
-
364
- exports['default'] = class PlatformCacheModule {};
365
- exports['default'] = tslib.__decorate([di.Module({
366
- imports: [exports.PlatformCache]
367
- })], exports['default']);
368
-
369
- exports.PlatformCacheModule = exports['default'];
370
- exports.UseCache = UseCache;
371
- exports.default = exports['default'];
372
- //# sourceMappingURL=index.js.map