Skip to content

Instantly share code, notes, and snippets.

@mmitou
Created July 23, 2023 05:38
Show Gist options
  • Save mmitou/604c7065bc7b75fe97f5684dc6ea1091 to your computer and use it in GitHub Desktop.
Save mmitou/604c7065bc7b75fe97f5684dc6ea1091 to your computer and use it in GitHub Desktop.
typescript decorator
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