Skip to content

Commit

Permalink
feat(decorators): add KbMeasure decorator
Browse files Browse the repository at this point in the history
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
  • Loading branch information
thatkookooguy committed May 18, 2021
1 parent 6af0bdd commit 0049de8
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
4 changes: 3 additions & 1 deletion server/src/api/api.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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));
}
}
1 change: 1 addition & 0 deletions server/src/decorators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
31 changes: 31 additions & 0 deletions server/src/decorators/kb-meature.ts
Original file line number Diff line number Diff line change
@@ -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;
};

0 comments on commit 0049de8

Please sign in to comment.