@tsed/platform-cache 7.5.3 → 7.6.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.
- package/lib/cjs/interceptors/PlatformCacheInterceptor.js +11 -5
- package/lib/cjs/interceptors/PlatformCacheInterceptor.js.map +1 -1
- package/lib/cjs/interfaces/PlatformCacheOptions.js.map +1 -1
- package/lib/esm/interceptors/PlatformCacheInterceptor.js +11 -5
- package/lib/esm/interceptors/PlatformCacheInterceptor.js.map +1 -1
- package/lib/esm/interfaces/PlatformCacheOptions.js.map +1 -1
- package/lib/types/interceptors/PlatformCacheInterceptor.d.ts +1 -0
- package/lib/types/interfaces/PlatformCacheOptions.d.ts +1 -0
- package/package.json +9 -9
|
@@ -47,12 +47,14 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
47
47
|
}
|
|
48
48
|
}
|
|
49
49
|
async cacheMethod(context, next) {
|
|
50
|
-
const { type, ttl, collectionType, refreshThreshold, keyArgs, args } = this.getOptions(context);
|
|
50
|
+
const { type, ttl, collectionType, refreshThreshold, keyArgs, args, canCache } = this.getOptions(context);
|
|
51
51
|
const key = [(0, core_1.nameOf)(context.target), context.propertyKey, keyArgs].join(":");
|
|
52
52
|
const set = (result) => {
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
53
|
+
if (!canCache || (canCache && canCache(result))) {
|
|
54
|
+
const calculatedTTL = this.cache.calculateTTL(result, ttl);
|
|
55
|
+
const data = (0, json_mapper_1.serialize)(result, { type, collectionType });
|
|
56
|
+
this.cache.setCachedObject(key, data, { args, ttl: calculatedTTL });
|
|
57
|
+
}
|
|
56
58
|
};
|
|
57
59
|
const cachedObject = await this.cache.getCachedObject(key);
|
|
58
60
|
if (!cachedObject) {
|
|
@@ -115,9 +117,13 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
115
117
|
}
|
|
116
118
|
getOptions(context) {
|
|
117
119
|
const { ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold } = context.options || {};
|
|
120
|
+
let { canCache } = context.options || {};
|
|
118
121
|
const args = this.getArgs(context);
|
|
119
122
|
const keyArgs = (0, core_1.isString)(k) ? k : k(args);
|
|
120
|
-
|
|
123
|
+
if (canCache && canCache === "no-nullish") {
|
|
124
|
+
canCache = (item) => ![null, undefined].includes(item);
|
|
125
|
+
}
|
|
126
|
+
return { refreshThreshold, ttl, type, args, collectionType, keyArgs, canCache };
|
|
121
127
|
}
|
|
122
128
|
isEndpoint({ target, propertyKey }) {
|
|
123
129
|
return core_1.Store.fromMethod(target, propertyKey).has(schema_1.JsonEntityStore);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PlatformCacheInterceptor.js","sourceRoot":"","sources":["../../../src/interceptors/PlatformCacheInterceptor.ts"],"names":[],"mappings":";;;;AAAA,qCAA4D;AAC5D,iCAA8H;AAC9H,mDAAyD;AACzD,yCAAoC;AACpC,yCAA6C;AAC7C,+BAAqD;AAGrD,6DAAwD;AAExD,MAAM,YAAY,GAAG,CAAC,OAAgC,EAAE,EAAE;IACxD,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC;SAC3B,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,gBAAgB,EAAE,cAAc,EAAE,eAAe,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;SACrF,MAAM,CAAC,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE;QAChC,OAAO;YACL,GAAG,OAAO;YACV,CAAC,GAAG,CAAC,EAAE,KAAK;SACb,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;AACX,CAAC,CAAC;AAEF;;GAEG;AAEH,IAAa,wBAAwB,GAArC,MAAa,wBAAwB;IAEzB,KAAK,CAAgB;IAGrB,MAAM,CAAS;IAEzB,KAAK,CAAC,SAAS,CAAC,OAAsD,EAAE,IA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,EAAE,WAAW,GAAG,EAAE;SAClC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;QAEd,OAAO,IAAI,CAAC;IACd,CAAC;CACF,CAAA;AA9KC;IADC,IAAA,WAAM,GAAE;sCACQ,6BAAa;uDAAC;AAG/B;IADC,IAAA,WAAM,GAAE;sCACS,eAAM;wDAAC;AALd,wBAAwB;IADpC,IAAA,gBAAW,GAAE;GACD,wBAAwB,CAgLpC;AAhLY,4DAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {Logger} from \"@tsed/logger\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n @Inject()\n protected logger: Logger;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL === undefined || currentTTL < calculatedTTL - refreshThreshold) {\n await next();\n }\n\n await this.deleteKeyFromQueue(key);\n }\n }\n\n async cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {type, ttl, collectionType, refreshThreshold, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const set = (result: any) => {\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n const data = serialize(result, {type, collectionType});\n this.cache.setCachedObject(key, data, {args, ttl: calculatedTTL});\n };\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (!cachedObject) {\n const result = await next();\n\n set(result);\n\n return result;\n }\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n await set(result);\n }).catch((er) =>\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"cacheMethod\",\n concerned_key: key,\n class_name: nameOf(context.target),\n property_key: context.propertyKey,\n error_description: er.message,\n stack: er.stack\n })\n );\n\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs};\n }\n\n protected isEndpoint({target, propertyKey}: InterceptorContext<any, PlatformCacheOptions>) {\n return Store.fromMethod(target, propertyKey).has(JsonEntityStore);\n }\n\n protected async hasKeyInQueue(key: string) {\n return !!(await this.cache.get(`$$queue:${key}`));\n }\n\n protected async addKeyToQueue(key: string) {\n await this.cache.set(`$$queue:${key}`, true, {ttl: 120});\n }\n\n protected async deleteKeyFromQueue(key: string) {\n await this.cache.del(`$$queue:${key}`);\n }\n\n protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext) {\n const {headers, ttl} = cachedObject;\n const {request, response} = $ctx;\n\n const requestEtag = request.get(\"if-none-match\");\n\n if (requestEtag && headers.etag === requestEtag) {\n response.status(304).setHeaders(headers).body(undefined);\n\n return undefined;\n }\n\n const data = JSON.parse(cachedObject.data);\n\n $ctx.response\n .setHeaders({\n ...headers,\n \"x-cached\": \"true\",\n \"cache-control\": `max-age=${ttl}`\n })\n .body(data);\n\n return data;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"PlatformCacheInterceptor.js","sourceRoot":"","sources":["../../../src/interceptors/PlatformCacheInterceptor.ts"],"names":[],"mappings":";;;;AAAA,qCAA4D;AAC5D,iCAA8H;AAC9H,mDAAyD;AACzD,yCAAoC;AACpC,yCAA6C;AAC7C,+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AA,gBAAW,GAAE;GACD,wBAAwB,CAwLpC;AAxLY,4DAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {Logger} from \"@tsed/logger\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n @Inject()\n protected logger: Logger;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL === undefined || 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, canCache} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const set = (result: any) => {\n if (!canCache || (canCache && canCache(result))) {\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\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (!cachedObject) {\n const result = await next();\n\n set(result);\n\n return result;\n }\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n\n await set(result);\n }).catch((er) =>\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"cacheMethod\",\n concerned_key: key,\n class_name: nameOf(context.target),\n property_key: context.propertyKey,\n error_description: er.message,\n stack: er.stack\n })\n );\n\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n let {canCache} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n if (canCache && canCache === \"no-nullish\") {\n canCache = (item: any) => ![null, undefined].includes(item);\n }\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs, canCache};\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 {Ttl} from \"../services/PlatformCache\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: Ttl;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n refreshThreshold?: number;\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 {Ttl} from \"../services/PlatformCache\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: Ttl;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n refreshThreshold?: number;\n canCache?: ((item: any) => boolean) | \"no-nullish\";\n}\n"]}
|
|
@@ -44,12 +44,14 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
44
44
|
}
|
|
45
45
|
}
|
|
46
46
|
async cacheMethod(context, next) {
|
|
47
|
-
const { type, ttl, collectionType, refreshThreshold, keyArgs, args } = this.getOptions(context);
|
|
47
|
+
const { type, ttl, collectionType, refreshThreshold, keyArgs, args, canCache } = this.getOptions(context);
|
|
48
48
|
const key = [nameOf(context.target), context.propertyKey, keyArgs].join(":");
|
|
49
49
|
const set = (result) => {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
50
|
+
if (!canCache || (canCache && canCache(result))) {
|
|
51
|
+
const calculatedTTL = this.cache.calculateTTL(result, ttl);
|
|
52
|
+
const data = serialize(result, { type, collectionType });
|
|
53
|
+
this.cache.setCachedObject(key, data, { args, ttl: calculatedTTL });
|
|
54
|
+
}
|
|
53
55
|
};
|
|
54
56
|
const cachedObject = await this.cache.getCachedObject(key);
|
|
55
57
|
if (!cachedObject) {
|
|
@@ -112,9 +114,13 @@ let PlatformCacheInterceptor = class PlatformCacheInterceptor {
|
|
|
112
114
|
}
|
|
113
115
|
getOptions(context) {
|
|
114
116
|
const { ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold } = context.options || {};
|
|
117
|
+
let { canCache } = context.options || {};
|
|
115
118
|
const args = this.getArgs(context);
|
|
116
119
|
const keyArgs = isString(k) ? k : k(args);
|
|
117
|
-
|
|
120
|
+
if (canCache && canCache === "no-nullish") {
|
|
121
|
+
canCache = (item) => ![null, undefined].includes(item);
|
|
122
|
+
}
|
|
123
|
+
return { refreshThreshold, ttl, type, args, collectionType, keyArgs, canCache };
|
|
118
124
|
}
|
|
119
125
|
isEndpoint({ target, propertyKey }) {
|
|
120
126
|
return Store.fromMethod(target, propertyKey).has(JsonEntityStore);
|
|
@@ -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,MAAM,EAAC,MAAM,cAAc,CAAC;AACpC,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,C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,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;AA9KC;IADC,MAAM,EAAE;8BACQ,aAAa;uDAAC;AAG/B;IADC,MAAM,EAAE;8BACS,MAAM;wDAAC;AALd,wBAAwB;IADpC,WAAW,EAAE;GACD,wBAAwB,CAgLpC;SAhLY,wBAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {Logger} from \"@tsed/logger\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n @Inject()\n protected logger: Logger;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL === undefined || currentTTL < calculatedTTL - refreshThreshold) {\n await next();\n }\n\n await this.deleteKeyFromQueue(key);\n }\n }\n\n async cacheMethod(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const {type, ttl, collectionType, refreshThreshold, keyArgs, args} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const set = (result: any) => {\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n const data = serialize(result, {type, collectionType});\n this.cache.setCachedObject(key, data, {args, ttl: calculatedTTL});\n };\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (!cachedObject) {\n const result = await next();\n\n set(result);\n\n return result;\n }\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n await set(result);\n }).catch((er) =>\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"cacheMethod\",\n concerned_key: key,\n class_name: nameOf(context.target),\n property_key: context.propertyKey,\n error_description: er.message,\n stack: er.stack\n })\n );\n\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs};\n }\n\n protected isEndpoint({target, propertyKey}: InterceptorContext<any, PlatformCacheOptions>) {\n return Store.fromMethod(target, propertyKey).has(JsonEntityStore);\n }\n\n protected async hasKeyInQueue(key: string) {\n return !!(await this.cache.get(`$$queue:${key}`));\n }\n\n protected async addKeyToQueue(key: string) {\n await this.cache.set(`$$queue:${key}`, true, {ttl: 120});\n }\n\n protected async deleteKeyFromQueue(key: string) {\n await this.cache.del(`$$queue:${key}`);\n }\n\n protected sendResponse(cachedObject: PlatformCachedObject, $ctx: BaseContext) {\n const {headers, ttl} = cachedObject;\n const {request, response} = $ctx;\n\n const requestEtag = request.get(\"if-none-match\");\n\n if (requestEtag && headers.etag === requestEtag) {\n response.status(304).setHeaders(headers).body(undefined);\n\n return undefined;\n }\n\n const data = JSON.parse(cachedObject.data);\n\n $ctx.response\n .setHeaders({\n ...headers,\n \"x-cached\": \"true\",\n \"cache-control\": `max-age=${ttl}`\n })\n .body(data);\n\n return data;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"PlatformCacheInterceptor.js","sourceRoot":"","sources":["../../../src/interceptors/PlatformCacheInterceptor.ts"],"names":[],"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C,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;AAtLC;IADC,MAAM,EAAE;8BACQ,aAAa;uDAAC;AAG/B;IADC,MAAM,EAAE;8BACS,MAAM;wDAAC;AALd,wBAAwB;IADpC,WAAW,EAAE;GACD,wBAAwB,CAwLpC;SAxLY,wBAAwB","sourcesContent":["import {isClass, isString, nameOf, Store} from \"@tsed/core\";\nimport {BaseContext, DIContext, Inject, Interceptor, InterceptorContext, InterceptorMethods, InterceptorNext} from \"@tsed/di\";\nimport {deserialize, serialize} from \"@tsed/json-mapper\";\nimport {Logger} from \"@tsed/logger\";\nimport {JsonEntityStore} from \"@tsed/schema\";\nimport {IncomingMessage, ServerResponse} from \"http\";\nimport {PlatformCachedObject} from \"../interfaces/PlatformCachedObject\";\nimport {PlatformCacheOptions} from \"../interfaces/PlatformCacheOptions\";\nimport {PlatformCache} from \"../services/PlatformCache\";\n\nconst cleanHeaders = (headers: Record<string, unknown>) => {\n return Object.entries(headers)\n .filter(([key]) => ![\"content-length\", \"x-request-id\", \"cache-control\"].includes(key))\n .reduce((headers, [key, value]) => {\n return {\n ...headers,\n [key]: value\n };\n }, {});\n};\n\n/**\n * @platform\n */\n@Interceptor()\nexport class PlatformCacheInterceptor implements InterceptorMethods {\n @Inject()\n protected cache: PlatformCache;\n\n @Inject()\n protected logger: Logger;\n\n async intercept(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n if (this.cache.disabled()) {\n return next();\n }\n\n if (!this.isEndpoint(context)) {\n return this.cacheMethod(context, next);\n }\n\n return this.cacheResponse(context, next);\n }\n\n async canRefreshInBackground(key: string, {refreshThreshold, ttl}: {refreshThreshold?: number; ttl: any}, next: Function) {\n const inQueue = await this.hasKeyInQueue(key);\n\n if (refreshThreshold && !inQueue) {\n await this.addKeyToQueue(key);\n\n const currentTTL = await this.cache.ttl(key);\n const calculatedTTL = this.cache.calculateTTL(currentTTL, ttl);\n\n if (currentTTL === undefined || 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, canCache} = this.getOptions(context);\n const key = [nameOf(context.target), context.propertyKey, keyArgs].join(\":\");\n\n const set = (result: any) => {\n if (!canCache || (canCache && canCache(result))) {\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\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (!cachedObject) {\n const result = await next();\n\n set(result);\n\n return result;\n }\n\n this.canRefreshInBackground(key, {refreshThreshold, ttl}, async () => {\n const result = await next();\n\n await set(result);\n }).catch((er) =>\n this.logger.error({\n event: \"CACHE_ERROR\",\n method: \"cacheMethod\",\n concerned_key: key,\n class_name: nameOf(context.target),\n property_key: context.propertyKey,\n error_description: er.message,\n stack: er.stack\n })\n );\n\n const {data} = cachedObject;\n\n return deserialize(JSON.parse(data), {collectionType, type});\n }\n\n async cacheResponse(context: InterceptorContext<any, PlatformCacheOptions>, next: InterceptorNext) {\n const $ctx: BaseContext = context.args[context.args.length - 1];\n const {request, response} = $ctx;\n\n if (request.method !== \"GET\") {\n return next();\n }\n\n const {ttl, args, keyArgs} = this.getOptions(context);\n const key = [request.method, request.url, keyArgs].join(\":\");\n\n const cachedObject = await this.cache.getCachedObject(key);\n\n if (cachedObject && !(request.get(\"cache-control\") === \"no-cache\")) {\n return this.sendResponse(cachedObject, $ctx);\n }\n\n const result = await next();\n\n const calculatedTTL = this.cache.calculateTTL(result, ttl);\n\n $ctx.response.setHeaders({\n \"cache-control\": `max-age=${calculatedTTL}`\n });\n\n // cache final response with his headers and body\n response.onEnd(async () => {\n this.cache.setCachedObject(key, response.getBody(), {\n ttl: calculatedTTL,\n args,\n headers: cleanHeaders(response.getHeaders())\n });\n });\n\n return result;\n }\n\n protected getArgs(context: InterceptorContext<unknown, PlatformCacheOptions>) {\n return context.args.reduce((args, arg) => {\n if (arg instanceof DIContext || arg instanceof IncomingMessage || arg instanceof ServerResponse) {\n return args;\n }\n\n if (isClass(arg)) {\n return args.concat(serialize(arg));\n }\n\n return args.concat(arg);\n }, []);\n }\n\n protected getOptions(context: InterceptorContext<any, PlatformCacheOptions>) {\n const {ttl, type, collectionType, key: k = this.cache.defaultKeyResolver(), refreshThreshold} = context.options || {};\n let {canCache} = context.options || {};\n\n const args = this.getArgs(context);\n const keyArgs = isString(k) ? k : k(args);\n\n if (canCache && canCache === \"no-nullish\") {\n canCache = (item: any) => ![null, undefined].includes(item);\n }\n\n return {refreshThreshold, ttl, type, args, collectionType, keyArgs, canCache};\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 {Ttl} from \"../services/PlatformCache\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: Ttl;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n refreshThreshold?: number;\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 {Ttl} from \"../services/PlatformCache\";\n\nexport interface PlatformCacheOptions extends MetadataTypes {\n ttl?: Ttl;\n key?: string | ((args: any[], ctx?: BaseContext) => string);\n refreshThreshold?: number;\n canCache?: ((item: any) => boolean) | \"no-nullish\";\n}\n"]}
|
|
@@ -24,6 +24,7 @@ export declare class PlatformCacheInterceptor implements InterceptorMethods {
|
|
|
24
24
|
args: any;
|
|
25
25
|
collectionType: any;
|
|
26
26
|
keyArgs: string;
|
|
27
|
+
canCache: ((item: any) => boolean) | undefined;
|
|
27
28
|
};
|
|
28
29
|
protected isEndpoint({ target, propertyKey }: InterceptorContext<any, PlatformCacheOptions>): boolean;
|
|
29
30
|
protected hasKeyInQueue(key: string): Promise<boolean>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tsed/platform-cache",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.6.0",
|
|
4
4
|
"description": "Platform cache module for Ts.ED Framework",
|
|
5
5
|
"private": false,
|
|
6
6
|
"source": "./src/index.ts",
|
|
@@ -26,17 +26,17 @@
|
|
|
26
26
|
"tslib": "2.4.0"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@tsed/core": "7.
|
|
30
|
-
"@tsed/di": "7.
|
|
31
|
-
"@tsed/json-mapper": "7.
|
|
32
|
-
"@tsed/schema": "7.
|
|
29
|
+
"@tsed/core": "7.6.0",
|
|
30
|
+
"@tsed/di": "7.6.0",
|
|
31
|
+
"@tsed/json-mapper": "7.6.0",
|
|
32
|
+
"@tsed/schema": "7.6.0",
|
|
33
33
|
"@types/micromatch": "^4.0.1"
|
|
34
34
|
},
|
|
35
35
|
"peerDependencies": {
|
|
36
|
-
"@tsed/core": "^7.
|
|
37
|
-
"@tsed/di": "^7.
|
|
38
|
-
"@tsed/json-mapper": "^7.
|
|
39
|
-
"@tsed/schema": "^7.
|
|
36
|
+
"@tsed/core": "^7.6.0",
|
|
37
|
+
"@tsed/di": "^7.6.0",
|
|
38
|
+
"@tsed/json-mapper": "^7.6.0",
|
|
39
|
+
"@tsed/schema": "^7.6.0"
|
|
40
40
|
},
|
|
41
41
|
"peerDependenciesMeta": {
|
|
42
42
|
"@tsed/core": {
|