From 0049de8439ec3d163eb5acbc042742d9d43b89ab Mon Sep 17 00:00:00 2001 From: Neil Kalman Date: Tue, 18 May 2021 22:12:09 +0000 Subject: [PATCH] feat(decorators): add KbMeasure decorator this will wrap a method with a winston `startTimer()` and will inform how long the function ran. Added an example on the depricated API for now --- server/src/api/api.controller.ts | 4 +++- server/src/decorators/index.ts | 1 + server/src/decorators/kb-meature.ts | 31 +++++++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 server/src/decorators/kb-meature.ts diff --git a/server/src/api/api.controller.ts b/server/src/api/api.controller.ts index 8165ca3d..f7c13da4 100644 --- a/server/src/api/api.controller.ts +++ b/server/src/api/api.controller.ts @@ -9,6 +9,7 @@ import { ApiOkResponse, ApiOperation } from '@nestjs/swagger'; import { WinstonLogger } from '@kibibit/nestjs-winston'; import { ConfigService } from '@kb-config'; +import { KbMeasure } from '@kb-decorators'; import { ApiInfo } from '@kb-models'; @Controller('api') @@ -52,7 +53,8 @@ export class ApiController { @ApiOperation({ deprecated: true }) + @KbMeasure(ApiController.name) async deprecationTest() { - return new Promise((resolve) => setTimeout(() => resolve('hello'), 60000)); + return new Promise((resolve) => setTimeout(() => resolve('hello'), 6000)); } } diff --git a/server/src/decorators/index.ts b/server/src/decorators/index.ts index b76c92bf..d945aa8e 100644 --- a/server/src/decorators/index.ts +++ b/server/src/decorators/index.ts @@ -6,6 +6,7 @@ export * from './get-all.decorator'; export * from './get-one.decorator'; export * from './kb-api-validation-error-response.decorator'; export * from './kb-delete.decorator'; +export * from './kb-meature'; export * from './kb-patch.decorator'; export * from './kb-post.decorator'; export * from './kb-put.decorator'; diff --git a/server/src/decorators/kb-meature.ts b/server/src/decorators/kb-meature.ts new file mode 100644 index 00000000..aee8238e --- /dev/null +++ b/server/src/decorators/kb-meature.ts @@ -0,0 +1,31 @@ +import { WinstonLogger } from '@kibibit/nestjs-winston'; + +const logger = new WinstonLogger('KbMeasure'); + +export const KbMeasure = (controlerName?: string) => ( + target: unknown, + propertyKey: string, + descriptor: PropertyDescriptor +) => { + const originalMethod = descriptor.value; + + descriptor.value = async function (...args) { + logger.verbose(generateLogMessagge('START')); + const start = logger.startTimer(); + const result = await Promise.resolve(originalMethod.apply(this, args)); + start.done({ + level: 'verbose', + message: generateLogMessagge('END') + }); + return result; + + function generateLogMessagge(msg: string) { + return [ + `${ controlerName ? controlerName + '.' : '' }${ originalMethod.name }`, + `(${ args && args.length ? '...' : '' }) ${ msg }` + ].join(''); + } + }; + + return descriptor; +};