Home:ALL Converter>Create decorator with parameters and access the decorated function parameters

Create decorator with parameters and access the decorated function parameters

Ask Time:2020-03-08T20:57:38         Author:Udi Mazor

Json Formatter

I want to write a log decorator that logs every time the function (in which the decorator decorates) is called. I want to log a key that the decorator accepts as a parameter and the arguments that the function was sent with.

So far I know how to write a simple log function that logs the function arguments but cant accept any parameters:

export function logger(
  target: Object,
  key: string,
  descriptor: PropertyDescriptor
) {
  const original = descriptor.value;
  descriptor.value = function() {
    const targetName = target.constructor.name;
    const args = JSON.stringify(arguments);
    console.log(`Calling ${targetName}.${key} with ${JSON.stringify(arguments)}`);
    const result = original.apply(this, arguments);
    return result;
  };
  return descriptor;
}

I also know how to write a decorator that accepts parameters:

log(logData: { value: string; target?: string }) {
    return function(
      target: Object,
      key: string,
      descriptor: PropertyDescriptor
    ) {
      console.log(`Key: ${logData.value}, Target: ${logData.target}`);

    };
  }

So you probably can guess that I am missing a link here which is to write a log decorator that can accepts a key as a parameter and logs this key with the arguments that the decorated function was called with.

I have a working example of those 2 decorators here: https://stackblitz.com/edit/angular-udi-decorators?file=src%2Fapp%2Flogger.ts

Author:Udi Mazor,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/60587690/create-decorator-with-parameters-and-access-the-decorated-function-parameters
yy