I am trying to access parameter names in method decorator.
function log(filter: string[] = []) {
return function(
target: any,
propertyKey: string,
descriptor: PropertyDescriptor,
) {
const originalFunc = descriptor.value;
descriptor.value = async function(...args: any[]) {
this.logger.log(
`Start ${propertyKey} function`,
`${this.constructor.name}.${propertyKey}`,
);
// filter is parameter names: to not log them
this.logger.verbose(
`${propertyKey} function Input Parameters is ${args}`,
);
const result = await originalFunc.apply(this, args);
this.logger.verbose(`${propertyKey} function returned: ${result}`);
this.logger.log(`End ${propertyKey} function`);
return result;
};
return descriptor;
};
}
What I am trying to do is to write a logger decorator. this decorator would log method name with its args, and its result after the method has been ran. This is no problem, but I also want to filter on what param gets logged.
We don't know what params we would get, or how many cause this decorator would be used on variety of methods.
One way I could think of is to get the param names. for example: if the method has three params arbitraryMethod(name: string, age: number, married: boolean) , I would like to get this as something like:
argNames = ['name', 'age', 'married'];
argValues = ['Jack', 23, false];
Or get it in this way:
const args {
name: 'Jack',
age: 23,
married: false
};
There is some other way to filter, which is to get indexes instead of param names, and filter by it, but it wouldn't be elegant and nice and probably a little hard to use. So I avoid using this approach.
I am open to any other solution, if you have it. Thanks in advance.
You can access to the array of parameters when you are inside the decorator once you want to use the original function, as all of them are inside the args[] parameter
descriptor.value = function (...args: any[]) {
// now you can access to args[0, 1...]
// Call the original function if needed
return originalValue.apply(this, args);
};
Hope this helps,