Created
July 23, 2023 05:38
-
-
Save mmitou/604c7065bc7b75fe97f5684dc6ea1091 to your computer and use it in GitHub Desktop.
typescript decorator
This file contains hidden or 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
export function ClassName(name: string) { | |
return function actualDecorator<T, U = unknown>( | |
constructor: new (...args: T[]) => U, | |
arg: ClassDecoratorContext | |
) { | |
console.log(arg); | |
constructor.prototype.className = name; | |
}; | |
} | |
export function traceAsyncMethod(methodName: string) { | |
return function actualDecorator< | |
This extends { className?: string }, | |
Args extends unknown[], | |
Return | |
>( | |
originalAsyncMethod: (this: This, ...args: Args) => Promise<Return>, | |
arg: ClassMemberDecoratorContext | |
) { | |
console.log(arg); | |
return async function replacementMethod(this: This, ...args: Args): Promise<Return> { | |
const className = this.className ?? this.constructor.name; | |
const body: Record<string, unknown> = { | |
level: 'info', | |
className, | |
methodName | |
}; | |
console.log({ ...body, message: `Entering ${className}.${methodName}()` }); | |
const result = await originalAsyncMethod.apply(this, args); | |
console.log({ ...body, message: `Exiting ${className}.${methodName}()` }); | |
return result; | |
}; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment