I am trying to create a logger that will log something before all method calls (like performance tracking).
I am using JS decorators for this , the class and method decorator is like :
logger.ts:
//class decorator with code to apply log to all class methods
export async function logger(something): Promise<void> {
doSomething
}
// decorator
export async function logMethod(something): Promise<void> {
console.log()
something.apply(this,args)
}
in files with class i can use it as :
someclass.ts
@logger
export default class SomeClass extends BaseClass {
async somemethod(message: string): Promise<boolean> {
return "Hi";
}
}
But for non class methods i cannot use decorator. So i created a proxy object which does the same :
logProxy = function() {
return new Proxy(object, {
get(target, prop, receiver) {
console.log()
//do something
}
}
I use this proxy in non class files as :
somefile.ts:
export async function dosomething(): Promise<void> {
const endPoint = `${url}`;
await get(endPoint);
}
module.exports = logProxy(module.exports);
I have to do this for many files , is there a way to or better way to ensure module.exports calls the proxy for all import globally , or a way to over ride module.export such that
module.export = log(module.exports); , when ever its called