Using decorators to add client-side logging

One of the features we want to use in our client code is to be able to log method calls, along with the parameters that are passed into them. We have encountered this type of feature before when we looked at creating decorators. In this case, we want to create a Log decorator:

export function Log() {
return function(target: Object,
propertyName: string,
propertyDesciptor: PropertyDescriptor): PropertyDescriptor {
const method = propertyDesciptor.value;
propertyDesciptor.value = function(...args: unknown[]) {
const params = args.map(arg => JSON.stringify(arg)).join();
const result = method.apply(this, args);
if (args && args.length > 0) {
console.log(`Calling ${propertyName} with ${params}`);
} else {
console.log(`Calling ${propertyName}. No parameters present.`)
}
return result;
};
return propertyDesciptor;
}
}

The way that the Log decorator works is that it starts off by copying the method from propertyDescriptor.value. We then replace this method by creating a function that takes in any parameters that are passed into the method. Inside this inner function, we use args.map to create a stringified representation of the parameter and value, which then joins them together. After calling method.apply to run the method, we write out details pertaining to the method and parameters to the console. With the preceding code, we now have a simple mechanism to automatically log methods and parameters just by using @Log.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.124.232