Created
July 11, 2022 21:37
-
-
Save docentedev/4aab8f1d20447ec7ef0e045daad9ada7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Controller, Get, Param } from '@nestjs/common'; | |
import { AppService } from './app.service'; | |
function LogErrorDecorator(bubble = true) { | |
console.log('Start'); | |
return ( | |
target: any, | |
propertyKey: string, | |
propertyDescriptor: PropertyDescriptor, | |
) => { | |
// injectLogger(target, 'logger'); // this is the same as using constructor(private readonly logger: LoggerService) in a class | |
//get original method | |
const originalMethod = propertyDescriptor.value; | |
//redefine descriptor value within own function block | |
propertyDescriptor.value = async function (...args: any[]) { | |
try { | |
console.log('before'); | |
const starttime = Date.now(); | |
const result = await originalMethod.apply(this, args); | |
const endtime = Date.now(); | |
// log request | |
// const req: Request = args[reqPosition]; | |
// const res: Response = args[resPosition]; | |
// console.log(res.body); | |
// console.log(args); | |
console.log(`${target.constructor.name}.${propertyKey}()`); | |
console.log(result); | |
console.log(`${propertyKey} took ${endtime - starttime}ms`); | |
console.log('after'); | |
return result + ' From LogErrorDecorator'; | |
// return await originalMethod.apply(this, args); | |
} catch (error) { | |
const logger: any = console; //LoggerService = this.logger; | |
logger.setContext(target.constructor.name); | |
logger.error(error.message, error.stack); | |
// rethrow error, so it can bubble up | |
if (bubble) { | |
throw error; | |
} | |
} | |
}; | |
}; | |
} | |
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); | |
@Controller() | |
export class AppController { | |
constructor(private readonly appService: AppService) {} | |
@Get('/test/:id') | |
@LogErrorDecorator() | |
async getHello(@Param('id') id: string): Promise<string> { | |
await sleep(1000); | |
return this.appService.getHello() + id; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment