AOP in Node.js by decorators
I have found an exciting library for implementing cross-cutting concerns such as logging with decorators in the node.js applications. I'm fond of this syntax and I'm heavily used to using this code style in .Net applications too.
So you can write your business class like below:
// in file MyClass.j
const logError = require('./LogError')
class MyClass {
@logError
add(a, b) {
if (typeof a !== 'number' || typeof b !== 'number') {
throw new Error('only numbers allowed')
}
return a + b
}
And then define logError
// in file logError.j
const { AfterThrowing } = require('@northscaler/aspectify')
const logError = ({ thisJoinPoint, error }) => {
console.log(`ERROR: ${thisJoinPoint.fullName} threw ${error}`)
}
module.exports = AfterThrowing(logError)s
Isn't it beautiful?
When you are implementing Services, Controllers, or any other business-based classes, you will be able to devolve these concerns to other teams and make developers free from thinking about them.
Please share your experiences :)