@tsed/platform-cache 7.0.0-beta.3 → 7.0.0-beta.4
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.
- package/jest.config.js +14 -0
- package/lib/cjs/index.js +9 -3
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/interceptors/PlatformCacheInterceptor.js +61 -45
- package/lib/cjs/interceptors/PlatformCacheInterceptor.js.map +1 -1
- package/lib/cjs/interfaces/PlatformCacheOptions.js.map +1 -1
- package/lib/cjs/interfaces/interfaces.js +3 -0
- package/lib/cjs/interfaces/interfaces.js.map +1 -0
- package/lib/cjs/package.json +3 -0
- package/lib/cjs/services/PlatformCache.js +64 -13
- package/lib/cjs/services/PlatformCache.js.map +1 -1
- package/lib/esm/decorators/useCache.js +1 -1
- package/lib/esm/index.js +9 -3
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/interceptors/PlatformCacheInterceptor.js +59 -43
- package/lib/esm/interceptors/PlatformCacheInterceptor.js.map +1 -1
- package/lib/esm/interfaces/PlatformCacheOptions.js.map +1 -1
- package/lib/esm/interfaces/interfaces.js +2 -0
- package/lib/esm/interfaces/interfaces.js.map +1 -0
- package/lib/esm/package.json +3 -0
- package/lib/esm/services/PlatformCache.js +61 -10
- package/lib/esm/services/PlatformCache.js.map +1 -1
- package/lib/types/index.d.ts +8 -2
- package/lib/types/interceptors/PlatformCacheInterceptor.d.ts +10 -2
- package/lib/types/interfaces/PlatformCacheOptions.d.ts +1 -0
- package/lib/types/interfaces/{index.d.ts → interfaces.d.ts} +4 -1
- package/lib/types/services/PlatformCache.d.ts +18 -10
- package/package.json +33 -19
- package/readme.md +2 -3
- package/tsconfig.compile.esm.json +1 -12
- package/lib/cjs/interfaces/index.js +0 -5
- package/lib/cjs/interfaces/index.js.map +0 -1
- package/lib/esm/interfaces/index.js +0 -2
- package/lib/esm/interfaces/index.js.map +0 -1
package/jest.config.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// For a detailed explanation regarding each configuration property, visit:
|
|
2
|
+
// https://jestjs.io/docs/en/configuration.html
|
|
3
|
+
|
|
4
|
+
module.exports = {
|
|
5
|
+
...require("@tsed/jest-config")(__dirname, "platform-cache"),
|
|
6
|
+
coverageThreshold: {
|
|
7
|
+
global: {
|
|
8
|
+
branches: 94.12,
|
|
9
|
+
functions: 100,
|
|
10
|
+
lines: 100,
|
|
11
|
+
statements: 100
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
};
|
package/lib/cjs/index.js
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @file Automatically generated by barrelsby.
|
|
4
|
+
*/
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
6
|
const tslib_1 = require("tslib");
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
tslib_1.__exportStar(require("./decorators/useCache"), exports);
|
|
8
|
+
tslib_1.__exportStar(require("./interceptors/PlatformCacheInterceptor"), exports);
|
|
9
|
+
tslib_1.__exportStar(require("./interfaces/PlatformCacheOptions"), exports);
|
|
10
|
+
tslib_1.__exportStar(require("./interfaces/PlatformCachedObject"), exports);
|
|
11
|
+
tslib_1.__exportStar(require("./interfaces/interfaces"), exports);
|
|
12
|
+
tslib_1.__exportStar(require("./services/PlatformCache"), exports);
|
|
7
13
|
//# sourceMappingURL=index.js.map
|
package/lib/cjs/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;GAEG;;;AAEH,gEAAsC;AACtC,kFAAwD;AACxD,4EAAkD;AAClD,4EAAkD;AAClD,kEAAwC;AACxC,mEAAyC","sourcesContent":["/**\n * @file Automatically generated by barrelsby.\n */\n\nexport * from \"./decorators/useCache\";\nexport * from \"./interceptors/PlatformCacheInterceptor\";\nexport * from \"./interfaces/PlatformCacheOptions\";\nexport * from \"./interfaces/PlatformCachedObject\";\nexport * from \"./interfaces/interfaces\";\nexport * from \"./services/PlatformCache\";\n"]}
|
|
@@ -31,43 +31,37 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
31
31
|
}
|
|
32
32
|
return this.cacheResponse(context, next);
|
|
33
33
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
34
|
+
async canRefreshInBackground(key, { refreshThreshold, ttl }, next) {
|
|
35
|
+
const inQueue = await this.hasKeyInQueue(key);
|
|
36
|
+
if (refreshThreshold && !inQueue) {
|
|
37
|
+
await this.addKeyToQueue(key);
|
|
38
|
+
const currentTTL = await this.cache.ttl(key);
|
|
39
|
+
const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);
|
|
40
|
+
if (currentTTL < calculatedTTL - refreshThreshold) {
|
|
41
|
+
await next();
|
|
38
42
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
return args.concat(arg);
|
|
43
|
-
}, []);
|
|
44
|
-
}
|
|
45
|
-
getOptions(context) {
|
|
46
|
-
const { ttl, type, collectionType, key: k = this.cache.defaultKeyResolver() } = context.options || {};
|
|
47
|
-
const args = this.getArgs(context);
|
|
48
|
-
const keyArgs = (0, core_1.isString)(k) ? k : k(args);
|
|
49
|
-
return { ttl, type, args, collectionType, keyArgs };
|
|
50
|
-
}
|
|
51
|
-
isEndpoint({ target, propertyKey }) {
|
|
52
|
-
return core_1.Store.fromMethod(target, propertyKey).has(schema_1.JsonEntityStore);
|
|
43
|
+
await this.deleteKeyFromQueue(key);
|
|
44
|
+
}
|
|
53
45
|
}
|
|
54
46
|
async cacheMethod(context, next) {
|
|
55
|
-
const {
|
|
47
|
+
const { type, ttl, collectionType, refreshThreshold, keyArgs, args } = this.getOptions(context);
|
|
56
48
|
const key = [(0, core_1.nameOf)(context.target), context.propertyKey, keyArgs].join(":");
|
|
57
|
-
const cachedObject = await this.cache.
|
|
49
|
+
const cachedObject = await this.cache.getCachedObject(key);
|
|
50
|
+
const set = (result) => {
|
|
51
|
+
const calculatedTTL = this.cache.calculateTTL(result, ttl);
|
|
52
|
+
const data = (0, json_mapper_1.serialize)(result, { type, collectionType });
|
|
53
|
+
this.cache.setCachedObject(key, data, { args, ttl: calculatedTTL });
|
|
54
|
+
};
|
|
55
|
+
this.canRefreshInBackground(key, { refreshThreshold, ttl }, async () => {
|
|
56
|
+
const result = await next();
|
|
57
|
+
await set(result);
|
|
58
|
+
});
|
|
58
59
|
if (cachedObject) {
|
|
59
60
|
const { data } = cachedObject;
|
|
60
61
|
return (0, json_mapper_1.deserialize)(JSON.parse(data), { collectionType, type });
|
|
61
62
|
}
|
|
62
63
|
const result = await next();
|
|
63
|
-
|
|
64
|
-
await this.cache.set(key, {
|
|
65
|
-
ttl: calculatedTtl,
|
|
66
|
-
args,
|
|
67
|
-
data: JSON.stringify((0, json_mapper_1.serialize)(result, { type, collectionType }))
|
|
68
|
-
}, {
|
|
69
|
-
ttl: calculatedTtl
|
|
70
|
-
});
|
|
64
|
+
setTimeout(() => set(result));
|
|
71
65
|
return result;
|
|
72
66
|
}
|
|
73
67
|
async cacheResponse(context, next) {
|
|
@@ -78,32 +72,54 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
78
72
|
}
|
|
79
73
|
const { ttl, args, keyArgs } = this.getOptions(context);
|
|
80
74
|
const key = [request.method, request.url, keyArgs].join(":");
|
|
81
|
-
const cachedObject = await this.cache.
|
|
82
|
-
if (cachedObject && !(
|
|
75
|
+
const cachedObject = await this.cache.getCachedObject(key);
|
|
76
|
+
if (cachedObject && !(request.get("cache-control") === "no-cache")) {
|
|
83
77
|
return this.sendResponse(cachedObject, $ctx);
|
|
84
78
|
}
|
|
85
79
|
const result = await next();
|
|
86
|
-
const
|
|
87
|
-
const expires = calculatedTtl + Date.now() / 1000;
|
|
80
|
+
const calculatedTTL = this.cache.calculateTTL(result, ttl);
|
|
88
81
|
$ctx.response.setHeaders({
|
|
89
|
-
"cache-control": `max-age=${
|
|
82
|
+
"cache-control": `max-age=${calculatedTTL}`
|
|
90
83
|
});
|
|
91
84
|
// cache final response with his headers and body
|
|
92
85
|
response.onEnd(async () => {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
await this.cache.set(key, {
|
|
96
|
-
ttl: calculatedTtl,
|
|
86
|
+
this.cache.setCachedObject(key, response.getBody(), {
|
|
87
|
+
ttl: calculatedTTL,
|
|
97
88
|
args,
|
|
98
|
-
|
|
99
|
-
expires,
|
|
100
|
-
headers
|
|
101
|
-
}, {
|
|
102
|
-
ttl: calculatedTtl
|
|
89
|
+
headers: cleanHeaders(response.getHeaders())
|
|
103
90
|
});
|
|
104
91
|
});
|
|
105
92
|
return result;
|
|
106
93
|
}
|
|
94
|
+
getArgs(context) {
|
|
95
|
+
return context.args.reduce((args, arg) => {
|
|
96
|
+
if (arg instanceof di_1.DIContext || arg instanceof http_1.IncomingMessage || arg instanceof http_1.ServerResponse) {
|
|
97
|
+
return args;
|
|
98
|
+
}
|
|
99
|
+
if ((0, core_1.isClass)(arg)) {
|
|
100
|
+
return args.concat((0, json_mapper_1.serialize)(arg));
|
|
101
|
+
}
|
|
102
|
+
return args.concat(arg);
|
|
103
|
+
}, []);
|
|
104
|
+
}
|
|
105
|
+
getOptions(context) {
|
|
106
|
+
const { ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold } = context.options || {};
|
|
107
|
+
const args = this.getArgs(context);
|
|
108
|
+
const keyArgs = (0, core_1.isString)(k) ? k : k(args);
|
|
109
|
+
return { refreshThreshold, ttl, type, args, collectionType, keyArgs };
|
|
110
|
+
}
|
|
111
|
+
isEndpoint({ target, propertyKey }) {
|
|
112
|
+
return core_1.Store.fromMethod(target, propertyKey).has(schema_1.JsonEntityStore);
|
|
113
|
+
}
|
|
114
|
+
async hasKeyInQueue(key) {
|
|
115
|
+
return !!(await this.cache.get(`$$queue:${key}`));
|
|
116
|
+
}
|
|
117
|
+
async addKeyToQueue(key) {
|
|
118
|
+
await this.cache.set(`$$queue:${key}`, true, { ttl: 120 });
|
|
119
|
+
}
|
|
120
|
+
async deleteKeyFromQueue(key) {
|
|
121
|
+
await this.cache.del(`$$queue:${key}`);
|
|
122
|
+
}
|
|
107
123
|
sendResponse(cachedObject, $ctx) {
|
|
108
124
|
const { headers, ttl } = cachedObject;
|
|
109
125
|
const { request, response } = $ctx;
|
|
@@ -123,11 +139,11 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
123
139
|
return data;
|
|
124
140
|
}
|
|
125
141
|
};
|
|
126
|
-
|
|
142
|
+
tslib_1.__decorate([
|
|
127
143
|
(0, di_1.Inject)(),
|
|
128
|
-
|
|
144
|
+
tslib_1.__metadata("design:type", PlatformCache_1.PlatformCache)
|
|
129
145
|
], PlatformCacheInterceptor.prototype, "cache", void 0);
|
|
130
|
-
PlatformCacheInterceptor =
|
|
146
|
+
PlatformCacheInterceptor = tslib_1.__decorate([
|
|
131
147
|
(0, di_1.Interceptor)()
|
|
132
148
|
], PlatformCacheInterceptor);
|
|
133
149
|
exports.PlatformCacheInterceptor = 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,CA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G,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;AAhJC;IADC,IAAA,WAAM,GAAE;2CACQ,6BAAa;uDAAC;AAFpB,wBAAwB;IADpC,IAAA,gBAAW,GAAE;GACD,wBAAwB,CAkJpC;AAlJY,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 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()} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {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 cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {ttl, type, collectionType, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.get<PlatformCachedObject>(key);\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 const calculatedTtl = this.cache.ttl(result, ttl);\n\n await this.cache.set<PlatformCachedObject>(\n key,\n {\n ttl: calculatedTtl,\n args,\n data: JSON.stringify(serialize(result, {type, collectionType}))\n },\n {\n ttl: calculatedTtl\n }\n );\n\n return result;\n }\n\n protected 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\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.get<PlatformCachedObject>(key);\n\n if (cachedObject && !(response.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTtl = this.cache.ttl(result, ttl);\n const expires = calculatedTtl + Date.now() / 1000;\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 const data = JSON.stringify(response.getBody());\n const headers = cleanHeaders(response.getHeaders());\n\n await this.cache.set<PlatformCachedObject>(\n key,\n {\n ttl: calculatedTtl,\n args,\n data,\n expires,\n headers\n },\n {\n ttl: calculatedTtl\n }\n );\n });\n\n return result;\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,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,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC,CAAC;AAEF;;GAEG;AAEH,IAAa,wBAAwB,GAArC,MAAa,wBAAwB;IAInC,KAAK,CAAC,SAAS,CAAC,OAAsD,EAAE,IAAqB;QAC3F,IAAI,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,EAAE;YAC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G,CAAC,WAAW,GAAG,EAAE,EAAE,IAAI,EAAE,EAAC,GAAG,EAAE,GAAG,EAAC,CAAC,CAAC;IAC3D,CAAC;IAES,KAAK,CAAC,kBAAkB,CAAC,GAAW;QAC5C,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;AAjKC;IADC,IAAA,WAAM,GAAE;sCACQ,6BAAa;uDAAC;AAFpB,wBAAwB;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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlatformCacheOptions.js","sourceRoot":"","sources":["../../../src/interfaces/PlatformCacheOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {MetadataTypes} from \"@tsed/core\";\nimport {BaseContext} from \"@tsed/di\";\nimport type {TtlFunction} from \"cache-manager\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: number | TtlFunction;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"PlatformCacheOptions.js","sourceRoot":"","sources":["../../../src/interfaces/PlatformCacheOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {MetadataTypes} from \"@tsed/core\";\nimport {BaseContext} from \"@tsed/di\";\nimport type {TtlFunction} from \"cache-manager\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: number | TtlFunction;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n refreshThreshold?: number;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../src/interfaces/interfaces.ts"],"names":[],"mappings":"","sourcesContent":["import type {BaseContext} from \"@tsed/di\";\nimport type {Cache, CacheOptions, CachingConfig, Store} from \"cache-manager\";\nimport type {CacheManager} from \"../services/PlatformCache\";\n\nexport interface PlatformCacheSettings extends CacheOptions, CachingConfig {\n caches?: Cache[];\n store?:\n | \"memory\"\n | \"none\"\n | Store\n | {\n create(...args: any[]): Store;\n }\n | (() => any);\n max?: number;\n keyResolver?: (args: any[], ctx: BaseContext) => string;\n\n /**\n * You may pass in any other arguments these will be passed on to the `create` method of your store,\n * otherwise they will be ignored.\n */\n [key: string]: any;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace TsED {\n interface Configuration {\n cache?: PlatformCacheSettings | false;\n }\n }\n}\n\nexport interface OnCreateCacheManager {\n $onCreateCacheManager(cache: CacheManager): void | Promise<void>;\n}\n"]}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var _PlatformCache_cache;
|
|
2
3
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
4
|
exports.PlatformCache = void 0;
|
|
4
5
|
const tslib_1 = require("tslib");
|
|
5
6
|
const core_1 = require("@tsed/core");
|
|
6
7
|
const di_1 = require("@tsed/di");
|
|
7
8
|
const json_mapper_1 = require("@tsed/json-mapper");
|
|
9
|
+
const logger_1 = require("@tsed/logger");
|
|
8
10
|
const defaultKeyResolver = (args) => {
|
|
9
11
|
return args.map((arg) => ((0, core_1.isClass)(arg) ? JSON.stringify((0, json_mapper_1.serialize)(arg)) : arg)).join(":");
|
|
10
12
|
};
|
|
@@ -12,25 +14,37 @@ const defaultKeyResolver = (args) => {
|
|
|
12
14
|
* @platform
|
|
13
15
|
*/
|
|
14
16
|
let PlatformCache = class PlatformCache {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
+
constructor() {
|
|
18
|
+
_PlatformCache_cache.set(this, void 0);
|
|
19
|
+
}
|
|
20
|
+
get cache() {
|
|
21
|
+
return tslib_1.__classPrivateFieldGet(this, _PlatformCache_cache, "f");
|
|
17
22
|
}
|
|
18
23
|
async $onInit() {
|
|
19
24
|
const settings = this.settings.get("cache");
|
|
20
25
|
if (settings) {
|
|
21
|
-
this
|
|
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"));
|
|
22
28
|
}
|
|
23
29
|
}
|
|
30
|
+
disabled() {
|
|
31
|
+
return !this.settings.get("cache");
|
|
32
|
+
}
|
|
24
33
|
defaultKeyResolver() {
|
|
25
34
|
return this.settings.get("cache.keyResolver", defaultKeyResolver);
|
|
26
35
|
}
|
|
27
36
|
defaultTtl() {
|
|
28
37
|
return this.settings.get("cache.ttl");
|
|
29
38
|
}
|
|
30
|
-
|
|
39
|
+
calculateTTL(result, currentTtl) {
|
|
31
40
|
const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;
|
|
32
41
|
return (0, core_1.isFunction)(ttl) ? ttl(result) : ttl;
|
|
33
42
|
}
|
|
43
|
+
async ttl(key) {
|
|
44
|
+
if (this.cache && "store" in this.cache && this.cache.store.ttl) {
|
|
45
|
+
return this.cache.store.ttl(key);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
34
48
|
wrap(key, fetch, options) {
|
|
35
49
|
var _a;
|
|
36
50
|
if (!this.cache) {
|
|
@@ -46,6 +60,35 @@ let PlatformCache = class PlatformCache {
|
|
|
46
60
|
var _a;
|
|
47
61
|
return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.set(key, value, options);
|
|
48
62
|
}
|
|
63
|
+
async getCachedObject(key) {
|
|
64
|
+
try {
|
|
65
|
+
return await this.get(key);
|
|
66
|
+
}
|
|
67
|
+
catch (er) {
|
|
68
|
+
this.logger.error({
|
|
69
|
+
event: "CACHE_ERROR",
|
|
70
|
+
method: "getCachedObject",
|
|
71
|
+
error: er
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async setCachedObject(key, data, opts) {
|
|
76
|
+
try {
|
|
77
|
+
await this.set(key, {
|
|
78
|
+
...opts,
|
|
79
|
+
data: JSON.stringify(data)
|
|
80
|
+
}, {
|
|
81
|
+
ttl: opts.ttl
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
catch (er) {
|
|
85
|
+
this.logger.error({
|
|
86
|
+
event: "CACHE_ERROR",
|
|
87
|
+
method: "setCachedObject",
|
|
88
|
+
error: er
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
49
92
|
async del(key) {
|
|
50
93
|
var _a;
|
|
51
94
|
await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.del(key));
|
|
@@ -55,16 +98,15 @@ let PlatformCache = class PlatformCache {
|
|
|
55
98
|
// @ts-ignore
|
|
56
99
|
await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.reset());
|
|
57
100
|
}
|
|
58
|
-
async keys() {
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
return this.cache.keys();
|
|
101
|
+
async keys(...args) {
|
|
102
|
+
if (this.cache && "store" in this.cache && this.cache.store.keys) {
|
|
103
|
+
return this.cache.store.keys(...args);
|
|
62
104
|
}
|
|
63
105
|
// istanbul ignore next
|
|
64
106
|
return [];
|
|
65
107
|
}
|
|
66
108
|
async getMatchingKeys(patterns) {
|
|
67
|
-
const [keys, { default: micromatch }] = await Promise.all([this.keys(), Promise.resolve().then(() =>
|
|
109
|
+
const [keys, { default: micromatch }] = await Promise.all([this.keys(), Promise.resolve().then(() => tslib_1.__importStar(require("micromatch")))]);
|
|
68
110
|
return micromatch(keys, patterns);
|
|
69
111
|
}
|
|
70
112
|
async deleteMatchingKeys(patterns) {
|
|
@@ -75,7 +117,7 @@ let PlatformCache = class PlatformCache {
|
|
|
75
117
|
async createCacheManager(settings) {
|
|
76
118
|
const { caches, store = "memory", ttl, ...props } = settings;
|
|
77
119
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
78
|
-
const { default: cacheManager } = await Promise.resolve().then(() =>
|
|
120
|
+
const { default: cacheManager } = await Promise.resolve().then(() => tslib_1.__importStar(require("cache-manager")));
|
|
79
121
|
return (caches === null || caches === void 0 ? void 0 : caches.length)
|
|
80
122
|
? cacheManager.multiCaching(caches, { ...props })
|
|
81
123
|
: cacheManager.caching({
|
|
@@ -85,11 +127,20 @@ let PlatformCache = class PlatformCache {
|
|
|
85
127
|
});
|
|
86
128
|
}
|
|
87
129
|
};
|
|
88
|
-
(
|
|
130
|
+
_PlatformCache_cache = new WeakMap();
|
|
131
|
+
tslib_1.__decorate([
|
|
89
132
|
(0, di_1.Configuration)(),
|
|
90
|
-
|
|
133
|
+
tslib_1.__metadata("design:type", Object)
|
|
91
134
|
], PlatformCache.prototype, "settings", void 0);
|
|
92
|
-
|
|
135
|
+
tslib_1.__decorate([
|
|
136
|
+
(0, di_1.Inject)(),
|
|
137
|
+
tslib_1.__metadata("design:type", di_1.InjectorService)
|
|
138
|
+
], PlatformCache.prototype, "injector", void 0);
|
|
139
|
+
tslib_1.__decorate([
|
|
140
|
+
(0, di_1.Inject)(),
|
|
141
|
+
tslib_1.__metadata("design:type", logger_1.Logger)
|
|
142
|
+
], PlatformCache.prototype, "logger", void 0);
|
|
143
|
+
PlatformCache = tslib_1.__decorate([
|
|
93
144
|
(0, di_1.Module)()
|
|
94
145
|
], PlatformCache);
|
|
95
146
|
exports.PlatformCache = PlatformCache;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlatformCache.js","sourceRoot":"","sources":["../../../src/services/PlatformCache.ts"],"names":[],"mappings":"
|
|
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,CAA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Ae,CAAC,QAAQ,CAAC,CAAC;QAElD,MAAM,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QAE5D,OAAO,IAAI,CAAC;IACd,CAAC;IAES,KAAK,CAAC,kBAAkB,CAAC,QAA+B;QAChE,MAAM,EAAC,MAAM,EAAE,KAAK,GAAG,QAAQ,EAAE,GAAG,EAAE,GAAG,KAAK,EAAC,GAAG,QAAQ,CAAC;QAC3D,6DAA6D;QAC7D,MAAM,EAAC,OAAO,EAAE,YAAY,EAAC,GAAG,gEAAa,eAAe,GAAC,CAAC;QAE9D,OAAO,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,6 +1,6 @@
|
|
|
1
1
|
import { useDecorators } from "@tsed/core";
|
|
2
2
|
import { Intercept } from "@tsed/di";
|
|
3
|
-
import { PlatformCacheInterceptor } from "../interceptors/PlatformCacheInterceptor";
|
|
3
|
+
import { PlatformCacheInterceptor } from "../interceptors/PlatformCacheInterceptor.js";
|
|
4
4
|
export function UseCache(options = {}) {
|
|
5
5
|
return useDecorators(Intercept(PlatformCacheInterceptor, options));
|
|
6
6
|
}
|
package/lib/esm/index.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @file Automatically generated by barrelsby.
|
|
3
|
+
*/
|
|
4
|
+
export * from "./decorators/useCache.js";
|
|
5
|
+
export * from "./interceptors/PlatformCacheInterceptor.js";
|
|
6
|
+
export * from "./interfaces/PlatformCacheOptions.js";
|
|
7
|
+
export * from "./interfaces/PlatformCachedObject.js";
|
|
8
|
+
export * from "./interfaces/interfaces.js";
|
|
9
|
+
export * from "./services/PlatformCache.js";
|
|
4
10
|
//# sourceMappingURL=index.js.map
|
package/lib/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,uBAAuB,CAAC;AACtC,cAAc,yCAAyC,CAAC;AACxD,cAAc,mCAAmC,CAAC;AAClD,cAAc,mCAAmC,CAAC;AAClD,cAAc,yBAAyB,CAAC;AACxC,cAAc,0BAA0B,CAAC","sourcesContent":["/**\n * @file Automatically generated by barrelsby.\n */\n\nexport * from \"./decorators/useCache\";\nexport * from \"./interceptors/PlatformCacheInterceptor\";\nexport * from \"./interfaces/PlatformCacheOptions\";\nexport * from \"./interfaces/PlatformCachedObject\";\nexport * from \"./interfaces/interfaces\";\nexport * from \"./services/PlatformCache\";\n"]}
|
|
@@ -4,7 +4,7 @@ import { DIContext, Inject, Interceptor } from "@tsed/di";
|
|
|
4
4
|
import { deserialize, serialize } from "@tsed/json-mapper";
|
|
5
5
|
import { JsonEntityStore } from "@tsed/schema";
|
|
6
6
|
import { IncomingMessage, ServerResponse } from "http";
|
|
7
|
-
import { PlatformCache } from "../services/PlatformCache";
|
|
7
|
+
import { PlatformCache } from "../services/PlatformCache.js";
|
|
8
8
|
const cleanHeaders = (headers) => {
|
|
9
9
|
return Object.entries(headers)
|
|
10
10
|
.filter(([key]) => !["content-length", "x-request-id", "cache-control"].includes(key))
|
|
@@ -28,43 +28,37 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
28
28
|
}
|
|
29
29
|
return this.cacheResponse(context, next);
|
|
30
30
|
}
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
async canRefreshInBackground(key, { refreshThreshold, ttl }, next) {
|
|
32
|
+
const inQueue = await this.hasKeyInQueue(key);
|
|
33
|
+
if (refreshThreshold && !inQueue) {
|
|
34
|
+
await this.addKeyToQueue(key);
|
|
35
|
+
const currentTTL = await this.cache.ttl(key);
|
|
36
|
+
const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);
|
|
37
|
+
if (currentTTL < calculatedTTL - refreshThreshold) {
|
|
38
|
+
await next();
|
|
35
39
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
}
|
|
39
|
-
return args.concat(arg);
|
|
40
|
-
}, []);
|
|
41
|
-
}
|
|
42
|
-
getOptions(context) {
|
|
43
|
-
const { ttl, type, collectionType, key: k = this.cache.defaultKeyResolver() } = context.options || {};
|
|
44
|
-
const args = this.getArgs(context);
|
|
45
|
-
const keyArgs = isString(k) ? k : k(args);
|
|
46
|
-
return { ttl, type, args, collectionType, keyArgs };
|
|
47
|
-
}
|
|
48
|
-
isEndpoint({ target, propertyKey }) {
|
|
49
|
-
return Store.fromMethod(target, propertyKey).has(JsonEntityStore);
|
|
40
|
+
await this.deleteKeyFromQueue(key);
|
|
41
|
+
}
|
|
50
42
|
}
|
|
51
43
|
async cacheMethod(context, next) {
|
|
52
|
-
const {
|
|
44
|
+
const { type, ttl, collectionType, refreshThreshold, keyArgs, args } = this.getOptions(context);
|
|
53
45
|
const key = [nameOf(context.target), context.propertyKey, keyArgs].join(":");
|
|
54
|
-
const cachedObject = await this.cache.
|
|
46
|
+
const cachedObject = await this.cache.getCachedObject(key);
|
|
47
|
+
const set = (result) => {
|
|
48
|
+
const calculatedTTL = this.cache.calculateTTL(result, ttl);
|
|
49
|
+
const data = serialize(result, { type, collectionType });
|
|
50
|
+
this.cache.setCachedObject(key, data, { args, ttl: calculatedTTL });
|
|
51
|
+
};
|
|
52
|
+
this.canRefreshInBackground(key, { refreshThreshold, ttl }, async () => {
|
|
53
|
+
const result = await next();
|
|
54
|
+
await set(result);
|
|
55
|
+
});
|
|
55
56
|
if (cachedObject) {
|
|
56
57
|
const { data } = cachedObject;
|
|
57
58
|
return deserialize(JSON.parse(data), { collectionType, type });
|
|
58
59
|
}
|
|
59
60
|
const result = await next();
|
|
60
|
-
|
|
61
|
-
await this.cache.set(key, {
|
|
62
|
-
ttl: calculatedTtl,
|
|
63
|
-
args,
|
|
64
|
-
data: JSON.stringify(serialize(result, { type, collectionType }))
|
|
65
|
-
}, {
|
|
66
|
-
ttl: calculatedTtl
|
|
67
|
-
});
|
|
61
|
+
setTimeout(() => set(result));
|
|
68
62
|
return result;
|
|
69
63
|
}
|
|
70
64
|
async cacheResponse(context, next) {
|
|
@@ -75,32 +69,54 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
75
69
|
}
|
|
76
70
|
const { ttl, args, keyArgs } = this.getOptions(context);
|
|
77
71
|
const key = [request.method, request.url, keyArgs].join(":");
|
|
78
|
-
const cachedObject = await this.cache.
|
|
79
|
-
if (cachedObject && !(
|
|
72
|
+
const cachedObject = await this.cache.getCachedObject(key);
|
|
73
|
+
if (cachedObject && !(request.get("cache-control") === "no-cache")) {
|
|
80
74
|
return this.sendResponse(cachedObject, $ctx);
|
|
81
75
|
}
|
|
82
76
|
const result = await next();
|
|
83
|
-
const
|
|
84
|
-
const expires = calculatedTtl + Date.now() / 1000;
|
|
77
|
+
const calculatedTTL = this.cache.calculateTTL(result, ttl);
|
|
85
78
|
$ctx.response.setHeaders({
|
|
86
|
-
"cache-control": `max-age=${
|
|
79
|
+
"cache-control": `max-age=${calculatedTTL}`
|
|
87
80
|
});
|
|
88
81
|
// cache final response with his headers and body
|
|
89
82
|
response.onEnd(async () => {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
await this.cache.set(key, {
|
|
93
|
-
ttl: calculatedTtl,
|
|
83
|
+
this.cache.setCachedObject(key, response.getBody(), {
|
|
84
|
+
ttl: calculatedTTL,
|
|
94
85
|
args,
|
|
95
|
-
|
|
96
|
-
expires,
|
|
97
|
-
headers
|
|
98
|
-
}, {
|
|
99
|
-
ttl: calculatedTtl
|
|
86
|
+
headers: cleanHeaders(response.getHeaders())
|
|
100
87
|
});
|
|
101
88
|
});
|
|
102
89
|
return result;
|
|
103
90
|
}
|
|
91
|
+
getArgs(context) {
|
|
92
|
+
return context.args.reduce((args, arg) => {
|
|
93
|
+
if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {
|
|
94
|
+
return args;
|
|
95
|
+
}
|
|
96
|
+
if (isClass(arg)) {
|
|
97
|
+
return args.concat(serialize(arg));
|
|
98
|
+
}
|
|
99
|
+
return args.concat(arg);
|
|
100
|
+
}, []);
|
|
101
|
+
}
|
|
102
|
+
getOptions(context) {
|
|
103
|
+
const { ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold } = context.options || {};
|
|
104
|
+
const args = this.getArgs(context);
|
|
105
|
+
const keyArgs = isString(k) ? k : k(args);
|
|
106
|
+
return { refreshThreshold, ttl, type, args, collectionType, keyArgs };
|
|
107
|
+
}
|
|
108
|
+
isEndpoint({ target, propertyKey }) {
|
|
109
|
+
return Store.fromMethod(target, propertyKey).has(JsonEntityStore);
|
|
110
|
+
}
|
|
111
|
+
async hasKeyInQueue(key) {
|
|
112
|
+
return !!(await this.cache.get(`$$queue:${key}`));
|
|
113
|
+
}
|
|
114
|
+
async addKeyToQueue(key) {
|
|
115
|
+
await this.cache.set(`$$queue:${key}`, true, { ttl: 120 });
|
|
116
|
+
}
|
|
117
|
+
async deleteKeyFromQueue(key) {
|
|
118
|
+
await this.cache.del(`$$queue:${key}`);
|
|
119
|
+
}
|
|
104
120
|
sendResponse(cachedObject, $ctx) {
|
|
105
121
|
const { headers, ttl } = cachedObject;
|
|
106
122
|
const { request, response } = $ctx;
|
|
@@ -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,cAAc,EAAC,MAAM,MAAM,CAAC;AAGrD,OAAO,EAAC,aAAa,EAAC,MAAM,2BAA2B,CAAC;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,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC,CAAC;AAEF;;GAEG;AAEH,IAAa,wBAAwB,GAArC,MAAa,wBAAwB;IAInC,KAAK,CAAC,SAAS,CAAC,OAAsD,EAAE,IAAq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Q,CAAC,UAAU,EAAE,CAAC,CAAC;YAEpD,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAClB,GAAG,EACH;gBACE,GAAG,EAAE,aAAa;gBAClB,IAAI;gBACJ,IAAI;gBACJ,OAAO;gBACP,OAAO;aACR,EACD;gBACE,GAAG,EAAE,aAAa;aACnB,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,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;AAhJC;IADC,MAAM,EAAE;8BACQ,aAAa;uDAAC;AAFpB,wBAAwB;IADpC,WAAW,EAAE;GACD,wBAAwB,CAkJpC;SAlJY,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 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()} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {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 cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {ttl, type, collectionType, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.get<PlatformCachedObject>(key);\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 const calculatedTtl = this.cache.ttl(result, ttl);\n\n await this.cache.set<PlatformCachedObject>(\n key,\n {\n ttl: calculatedTtl,\n args,\n data: JSON.stringify(serialize(result, {type, collectionType}))\n },\n {\n ttl: calculatedTtl\n }\n );\n\n return result;\n }\n\n protected 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\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.get<PlatformCachedObject>(key);\n\n if (cachedObject && !(response.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTtl = this.cache.ttl(result, ttl);\n const expires = calculatedTtl + Date.now() / 1000;\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 const data = JSON.stringify(response.getBody());\n const headers = cleanHeaders(response.getHeaders());\n\n await this.cache.set<PlatformCachedObject>(\n key,\n {\n ttl: calculatedTtl,\n args,\n data,\n expires,\n headers\n },\n {\n ttl: calculatedTtl\n }\n );\n });\n\n return result;\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 }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C,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;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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlatformCacheOptions.js","sourceRoot":"","sources":["../../../src/interfaces/PlatformCacheOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {MetadataTypes} from \"@tsed/core\";\nimport {BaseContext} from \"@tsed/di\";\nimport type {TtlFunction} from \"cache-manager\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: number | TtlFunction;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"PlatformCacheOptions.js","sourceRoot":"","sources":["../../../src/interfaces/PlatformCacheOptions.ts"],"names":[],"mappings":"","sourcesContent":["import {MetadataTypes} from \"@tsed/core\";\nimport {BaseContext} from \"@tsed/di\";\nimport type {TtlFunction} from \"cache-manager\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: number | TtlFunction;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n refreshThreshold?: number;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"interfaces.js","sourceRoot":"","sources":["../../../src/interfaces/interfaces.ts"],"names":[],"mappings":"","sourcesContent":["import type {BaseContext} from \"@tsed/di\";\nimport type {Cache, CacheOptions, CachingConfig, Store} from \"cache-manager\";\nimport type {CacheManager} from \"../services/PlatformCache\";\n\nexport interface PlatformCacheSettings extends CacheOptions, CachingConfig {\n caches?: Cache[];\n store?:\n | \"memory\"\n | \"none\"\n | Store\n | {\n create(...args: any[]): Store;\n }\n | (() => any);\n max?: number;\n keyResolver?: (args: any[], ctx: BaseContext) => string;\n\n /**\n * You may pass in any other arguments these will be passed on to the `create` method of your store,\n * otherwise they will be ignored.\n */\n [key: string]: any;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace TsED {\n interface Configuration {\n cache?: PlatformCacheSettings | false;\n }\n }\n}\n\nexport interface OnCreateCacheManager {\n $onCreateCacheManager(cache: CacheManager): void | Promise<void>;\n}\n"]}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
|
|
1
|
+
var _PlatformCache_cache;
|
|
2
|
+
import { __classPrivateFieldGet, __classPrivateFieldSet, __decorate, __metadata } from "tslib";
|
|
2
3
|
import { isClass, isFunction } from "@tsed/core";
|
|
3
|
-
import { Configuration, Module } from "@tsed/di";
|
|
4
|
+
import { Configuration, Inject, InjectorService, Module } from "@tsed/di";
|
|
4
5
|
import { deserialize, serialize } from "@tsed/json-mapper";
|
|
6
|
+
import { Logger } from "@tsed/logger";
|
|
5
7
|
const defaultKeyResolver = (args) => {
|
|
6
8
|
return args.map((arg) => (isClass(arg) ? JSON.stringify(serialize(arg)) : arg)).join(":");
|
|
7
9
|
};
|
|
@@ -9,25 +11,37 @@ const defaultKeyResolver = (args) => {
|
|
|
9
11
|
* @platform
|
|
10
12
|
*/
|
|
11
13
|
let PlatformCache = class PlatformCache {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
+
constructor() {
|
|
15
|
+
_PlatformCache_cache.set(this, void 0);
|
|
16
|
+
}
|
|
17
|
+
get cache() {
|
|
18
|
+
return __classPrivateFieldGet(this, _PlatformCache_cache, "f");
|
|
14
19
|
}
|
|
15
20
|
async $onInit() {
|
|
16
21
|
const settings = this.settings.get("cache");
|
|
17
22
|
if (settings) {
|
|
18
|
-
this
|
|
23
|
+
__classPrivateFieldSet(this, _PlatformCache_cache, await this.createCacheManager(settings), "f");
|
|
24
|
+
await this.injector.emit("$onCreateCacheManager", __classPrivateFieldGet(this, _PlatformCache_cache, "f"));
|
|
19
25
|
}
|
|
20
26
|
}
|
|
27
|
+
disabled() {
|
|
28
|
+
return !this.settings.get("cache");
|
|
29
|
+
}
|
|
21
30
|
defaultKeyResolver() {
|
|
22
31
|
return this.settings.get("cache.keyResolver", defaultKeyResolver);
|
|
23
32
|
}
|
|
24
33
|
defaultTtl() {
|
|
25
34
|
return this.settings.get("cache.ttl");
|
|
26
35
|
}
|
|
27
|
-
|
|
36
|
+
calculateTTL(result, currentTtl) {
|
|
28
37
|
const ttl = currentTtl === undefined ? this.defaultTtl() : currentTtl;
|
|
29
38
|
return isFunction(ttl) ? ttl(result) : ttl;
|
|
30
39
|
}
|
|
40
|
+
async ttl(key) {
|
|
41
|
+
if (this.cache && "store" in this.cache && this.cache.store.ttl) {
|
|
42
|
+
return this.cache.store.ttl(key);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
31
45
|
wrap(key, fetch, options) {
|
|
32
46
|
var _a;
|
|
33
47
|
if (!this.cache) {
|
|
@@ -43,6 +57,35 @@ let PlatformCache = class PlatformCache {
|
|
|
43
57
|
var _a;
|
|
44
58
|
return (_a = this.cache) === null || _a === void 0 ? void 0 : _a.set(key, value, options);
|
|
45
59
|
}
|
|
60
|
+
async getCachedObject(key) {
|
|
61
|
+
try {
|
|
62
|
+
return await this.get(key);
|
|
63
|
+
}
|
|
64
|
+
catch (er) {
|
|
65
|
+
this.logger.error({
|
|
66
|
+
event: "CACHE_ERROR",
|
|
67
|
+
method: "getCachedObject",
|
|
68
|
+
error: er
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async setCachedObject(key, data, opts) {
|
|
73
|
+
try {
|
|
74
|
+
await this.set(key, {
|
|
75
|
+
...opts,
|
|
76
|
+
data: JSON.stringify(data)
|
|
77
|
+
}, {
|
|
78
|
+
ttl: opts.ttl
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
catch (er) {
|
|
82
|
+
this.logger.error({
|
|
83
|
+
event: "CACHE_ERROR",
|
|
84
|
+
method: "setCachedObject",
|
|
85
|
+
error: er
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
}
|
|
46
89
|
async del(key) {
|
|
47
90
|
var _a;
|
|
48
91
|
await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.del(key));
|
|
@@ -52,10 +95,9 @@ let PlatformCache = class PlatformCache {
|
|
|
52
95
|
// @ts-ignore
|
|
53
96
|
await ((_a = this.cache) === null || _a === void 0 ? void 0 : _a.reset());
|
|
54
97
|
}
|
|
55
|
-
async keys() {
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
return this.cache.keys();
|
|
98
|
+
async keys(...args) {
|
|
99
|
+
if (this.cache && "store" in this.cache && this.cache.store.keys) {
|
|
100
|
+
return this.cache.store.keys(...args);
|
|
59
101
|
}
|
|
60
102
|
// istanbul ignore next
|
|
61
103
|
return [];
|
|
@@ -82,10 +124,19 @@ let PlatformCache = class PlatformCache {
|
|
|
82
124
|
});
|
|
83
125
|
}
|
|
84
126
|
};
|
|
127
|
+
_PlatformCache_cache = new WeakMap();
|
|
85
128
|
__decorate([
|
|
86
129
|
Configuration(),
|
|
87
130
|
__metadata("design:type", Object)
|
|
88
131
|
], PlatformCache.prototype, "settings", void 0);
|
|
132
|
+
__decorate([
|
|
133
|
+
Inject(),
|
|
134
|
+
__metadata("design:type", InjectorService)
|
|
135
|
+
], PlatformCache.prototype, "injector", void 0);
|
|
136
|
+
__decorate([
|
|
137
|
+
Inject(),
|
|
138
|
+
__metadata("design:type", Logger)
|
|
139
|
+
], PlatformCache.prototype, "logger", void 0);
|
|
89
140
|
PlatformCache = __decorate([
|
|
90
141
|
Module()
|
|
91
142
|
], PlatformCache);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlatformCache.js","sourceRoot":"","sources":["../../../src/services/PlatformCache.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"PlatformCache.js","sourceRoot":"","sources":["../../../src/services/PlatformCache.ts"],"names":[],"mappings":";;AAAA,OAAO,EAAC,OAAO,EAAE,UAA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GlC;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"]}
|
package/lib/types/index.d.ts
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @file Automatically generated by barrelsby.
|
|
3
|
+
*/
|
|
3
4
|
export * from "./decorators/useCache";
|
|
5
|
+
export * from "./interceptors/PlatformCacheInterceptor";
|
|
6
|
+
export * from "./interfaces/PlatformCacheOptions";
|
|
7
|
+
export * from "./interfaces/PlatformCachedObject";
|
|
8
|
+
export * from "./interfaces/interfaces";
|
|
9
|
+
export * from "./services/PlatformCache";
|
|
@@ -8,8 +8,15 @@ import { PlatformCache } from "../services/PlatformCache";
|
|
|
8
8
|
export declare class PlatformCacheInterceptor implements InterceptorMethods {
|
|
9
9
|
protected cache: PlatformCache;
|
|
10
10
|
intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext): Promise<any>;
|
|
11
|
+
canRefreshInBackground(key: string, { refreshThreshold, ttl }: {
|
|
12
|
+
refreshThreshold?: number;
|
|
13
|
+
ttl: any;
|
|
14
|
+
}, next: Function): Promise<void>;
|
|
15
|
+
cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext): Promise<any>;
|
|
16
|
+
cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext): Promise<any>;
|
|
11
17
|
protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>): any;
|
|
12
18
|
protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>): {
|
|
19
|
+
refreshThreshold: number | undefined;
|
|
13
20
|
ttl: number | import("cache-manager").TtlFunction | undefined;
|
|
14
21
|
type: any;
|
|
15
22
|
args: any;
|
|
@@ -17,7 +24,8 @@ export declare class PlatformCacheInterceptor implements InterceptorMethods {
|
|
|
17
24
|
keyArgs: string;
|
|
18
25
|
};
|
|
19
26
|
protected isEndpoint({ target, propertyKey }: InterceptorContext<any, PlatformCacheOptions>): boolean;
|
|
20
|
-
protected
|
|
21
|
-
protected
|
|
27
|
+
protected hasKeyInQueue(key: string): Promise<boolean>;
|
|
28
|
+
protected addKeyToQueue(key: string): Promise<void>;
|
|
29
|
+
protected deleteKeyFromQueue(key: string): Promise<void>;
|
|
22
30
|
protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext): any;
|
|
23
31
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { BaseContext } from "@tsed/di";
|
|
2
2
|
import type { Cache, CacheOptions, CachingConfig, Store } from "cache-manager";
|
|
3
|
-
|
|
3
|
+
import type { CacheManager } from "../services/PlatformCache";
|
|
4
4
|
export interface PlatformCacheSettings extends CacheOptions, CachingConfig {
|
|
5
5
|
caches?: Cache[];
|
|
6
6
|
store?: "memory" | "none" | Store | {
|
|
@@ -21,3 +21,6 @@ declare global {
|
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
|
+
export interface OnCreateCacheManager {
|
|
25
|
+
$onCreateCacheManager(cache: CacheManager): void | Promise<void>;
|
|
26
|
+
}
|
|
@@ -1,27 +1,35 @@
|
|
|
1
|
-
import { Configuration } from "@tsed/di";
|
|
1
|
+
import { Configuration, InjectorService } from "@tsed/di";
|
|
2
2
|
import { JsonDeserializerOptions } from "@tsed/json-mapper";
|
|
3
3
|
import type { Cache, CachingConfig, MultiCache, TtlFunction } from "cache-manager";
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
import { PlatformCachedObject } from "../interfaces/PlatformCachedObject";
|
|
5
|
+
import { PlatformCacheSettings } from "../interfaces/interfaces";
|
|
6
|
+
import { Logger } from "@tsed/logger";
|
|
7
|
+
export declare type CacheManager = Cache | MultiCache;
|
|
8
8
|
/**
|
|
9
9
|
* @platform
|
|
10
10
|
*/
|
|
11
11
|
export declare class PlatformCache {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
12
|
+
#private;
|
|
13
|
+
protected settings: Configuration;
|
|
14
|
+
protected injector: InjectorService;
|
|
15
|
+
protected logger: Logger;
|
|
16
|
+
get cache(): CacheManager | undefined;
|
|
15
17
|
$onInit(): Promise<void>;
|
|
18
|
+
disabled(): boolean;
|
|
16
19
|
defaultKeyResolver(): (args: any[], ctx?: any) => string;
|
|
17
20
|
defaultTtl(): number | TtlFunction;
|
|
18
|
-
|
|
21
|
+
calculateTTL(result?: any, currentTtl?: number | TtlFunction): number;
|
|
22
|
+
ttl(key: string): Promise<any>;
|
|
19
23
|
wrap<T>(key: string, fetch: () => Promise<T>, options?: CachingConfig): Promise<T>;
|
|
20
24
|
get<T>(key: string, options?: JsonDeserializerOptions): Promise<T | undefined>;
|
|
21
25
|
set<T>(key: string, value: any, options?: CachingConfig): Promise<T | undefined>;
|
|
26
|
+
getCachedObject(key: string): Promise<PlatformCachedObject | undefined>;
|
|
27
|
+
setCachedObject(key: string, data: any, opts: {
|
|
28
|
+
ttl: number;
|
|
29
|
+
} & Record<string, any>): Promise<void>;
|
|
22
30
|
del(key: string): Promise<void>;
|
|
23
31
|
reset(): Promise<void>;
|
|
24
|
-
keys(): Promise<string[]>;
|
|
32
|
+
keys(...args: any[]): Promise<string[]>;
|
|
25
33
|
getMatchingKeys(patterns: string): Promise<string[]>;
|
|
26
34
|
deleteMatchingKeys(patterns: string): Promise<string[]>;
|
|
27
35
|
protected createCacheManager(settings: PlatformCacheSettings): Promise<MultiCache>;
|
package/package.json
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tsed/platform-cache",
|
|
3
|
-
"version": "7.0.0-beta.
|
|
3
|
+
"version": "7.0.0-beta.4",
|
|
4
4
|
"description": "Platform cache module for Ts.ED Framework",
|
|
5
5
|
"private": false,
|
|
6
6
|
"source": "./src/index.ts",
|
|
7
7
|
"main": "./lib/cjs/index.js",
|
|
8
|
+
"module": "./lib/esm/index.js",
|
|
8
9
|
"typings": "./lib/types/index.d.ts",
|
|
9
10
|
"exports": {
|
|
10
11
|
"types": "./lib/types/index.d.ts",
|
|
@@ -13,37 +14,50 @@
|
|
|
13
14
|
"default": "./lib/esm/index.js"
|
|
14
15
|
},
|
|
15
16
|
"scripts": {
|
|
16
|
-
"build": "yarn run build:esm && yarn run build:cjs",
|
|
17
|
+
"build": "yarn barrels && yarn run build:esm && yarn run build:cjs",
|
|
17
18
|
"build:cjs": "tsc --build tsconfig.compile.json",
|
|
18
|
-
"build:esm": "tsc --build tsconfig.compile.esm.json"
|
|
19
|
+
"build:esm": "tsc --build tsconfig.compile.esm.json",
|
|
20
|
+
"test": "cross-env NODE_ENV=test yarn jest --max-workers=2",
|
|
21
|
+
"barrels": "yarn barrelsby --delete -d ./src -e \"\\.spec\\.ts\" -e \"__mock__\" -e \".benchmark.ts\""
|
|
19
22
|
},
|
|
20
23
|
"dependencies": {
|
|
21
|
-
"@types/cache-manager": "^3.4.
|
|
22
|
-
"cache-manager": "^3.
|
|
23
|
-
"micromatch": "
|
|
24
|
-
"tslib": "2.
|
|
24
|
+
"@types/cache-manager": "^3.4.3",
|
|
25
|
+
"cache-manager": "^3.6.0",
|
|
26
|
+
"micromatch": "4.0.5",
|
|
27
|
+
"tslib": "2.3.1"
|
|
25
28
|
},
|
|
26
29
|
"devDependencies": {
|
|
27
|
-
"@tsed/core": "7.0.0-beta.
|
|
28
|
-
"@tsed/di": "7.0.0-beta.
|
|
29
|
-
"@tsed/
|
|
30
|
-
"@tsed/
|
|
31
|
-
"@tsed/schema": "7.0.0-beta.3",
|
|
32
|
-
"@types/cache-manager": "^3.4.2",
|
|
30
|
+
"@tsed/core": "7.0.0-beta.4",
|
|
31
|
+
"@tsed/di": "7.0.0-beta.4",
|
|
32
|
+
"@tsed/json-mapper": "7.0.0-beta.4",
|
|
33
|
+
"@tsed/schema": "7.0.0-beta.4",
|
|
33
34
|
"@types/micromatch": "^4.0.1"
|
|
34
35
|
},
|
|
35
36
|
"peerDependencies": {
|
|
36
|
-
"@tsed/core": "^7.0.0-beta.
|
|
37
|
-
"@tsed/di": "^7.0.0-beta.
|
|
38
|
-
"@tsed/
|
|
39
|
-
"@tsed/
|
|
40
|
-
|
|
37
|
+
"@tsed/core": "^7.0.0-beta.4",
|
|
38
|
+
"@tsed/di": "^7.0.0-beta.4",
|
|
39
|
+
"@tsed/json-mapper": "^7.0.0-beta.4",
|
|
40
|
+
"@tsed/schema": "^7.0.0-beta.4"
|
|
41
|
+
},
|
|
42
|
+
"peerDependenciesMeta": {
|
|
43
|
+
"@tsed/core": {
|
|
44
|
+
"optional": false
|
|
45
|
+
},
|
|
46
|
+
"@tsed/di": {
|
|
47
|
+
"optional": false
|
|
48
|
+
},
|
|
49
|
+
"@tsed/json-mapper": {
|
|
50
|
+
"optional": false
|
|
51
|
+
},
|
|
52
|
+
"@tsed/schema": {
|
|
53
|
+
"optional": false
|
|
54
|
+
}
|
|
41
55
|
},
|
|
42
56
|
"repository": "https://github.com/tsedio/tsed",
|
|
43
57
|
"bugs": {
|
|
44
58
|
"url": "https://github.com/tsedio/tsed/issues"
|
|
45
59
|
},
|
|
46
|
-
"homepage": "https://github.com/tsedio/tsed/tree/
|
|
60
|
+
"homepage": "https://github.com/tsedio/tsed/tree/production/packages/platform/platform-cache",
|
|
47
61
|
"author": "Romain Lenzotti",
|
|
48
62
|
"license": "MIT"
|
|
49
63
|
}
|
package/readme.md
CHANGED
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
|
|
28
28
|
<hr />
|
|
29
29
|
|
|
30
|
-
A package of Ts.ED framework. See website: https://tsed.io/
|
|
30
|
+
A package of Ts.ED framework. See website: https://tsed.io/docs/cache.html
|
|
31
31
|
|
|
32
32
|
# Installation
|
|
33
33
|
|
|
@@ -36,18 +36,17 @@ npm install --save @tsed/platform-cache
|
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
## Contributors
|
|
39
|
+
|
|
39
40
|
Please read [contributing guidelines here](https://tsed.io/CONTRIBUTING.html).
|
|
40
41
|
|
|
41
42
|
<a href="https://github.com/tsedio/ts-express-decorators/graphs/contributors"><img src="https://opencollective.com/tsed/contributors.svg?width=890" /></a>
|
|
42
43
|
|
|
43
|
-
|
|
44
44
|
## Backers
|
|
45
45
|
|
|
46
46
|
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/tsed#backer)]
|
|
47
47
|
|
|
48
48
|
<a href="https://opencollective.com/tsed#backers" target="_blank"><img src="https://opencollective.com/tsed/tiers/backer.svg?width=890"></a>
|
|
49
49
|
|
|
50
|
-
|
|
51
50
|
## Sponsors
|
|
52
51
|
|
|
53
52
|
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/tsed#sponsor)]
|
|
@@ -8,16 +8,5 @@
|
|
|
8
8
|
"declaration": true,
|
|
9
9
|
"declarationDir": "./lib/types"
|
|
10
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
|
-
]
|
|
11
|
+
"exclude": ["node_modules", "test", "lib", "benchmark", "coverage", "spec", "**/*.benchmark.ts", "**/*.spec.ts", "keys", "jest.config.js"]
|
|
23
12
|
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/interfaces/index.ts"],"names":[],"mappings":";;;AAGA,sEAAuC","sourcesContent":["import type {BaseContext} from \"@tsed/di\";\nimport type {Cache, CacheOptions, CachingConfig, Store} from \"cache-manager\";\n\nexport * from \"./PlatformCachedObject\";\n\nexport interface PlatformCacheSettings extends CacheOptions, CachingConfig {\n caches?: Cache[];\n store?:\n | \"memory\"\n | \"none\"\n | Store\n | {\n create(...args: any[]): Store;\n }\n | (() => any);\n max?: number;\n keyResolver?: (args: any[], ctx: BaseContext) => string;\n\n /**\n * You may pass in any other arguments these will be passed on to the `create` method of your store,\n * otherwise they will be ignored.\n */\n [key: string]: any;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace TsED {\n interface Configuration {\n cache?: PlatformCacheSettings | false;\n }\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/interfaces/index.ts"],"names":[],"mappings":"AAGA,cAAc,wBAAwB,CAAC","sourcesContent":["import type {BaseContext} from \"@tsed/di\";\nimport type {Cache, CacheOptions, CachingConfig, Store} from \"cache-manager\";\n\nexport * from \"./PlatformCachedObject\";\n\nexport interface PlatformCacheSettings extends CacheOptions, CachingConfig {\n caches?: Cache[];\n store?:\n | \"memory\"\n | \"none\"\n | Store\n | {\n create(...args: any[]): Store;\n }\n | (() => any);\n max?: number;\n keyResolver?: (args: any[], ctx: BaseContext) => string;\n\n /**\n * You may pass in any other arguments these will be passed on to the `create` method of your store,\n * otherwise they will be ignored.\n */\n [key: string]: any;\n}\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/no-namespace\n namespace TsED {\n interface Configuration {\n cache?: PlatformCacheSettings | false;\n }\n }\n}\n"]}
|