AOP in Node.js by decorators

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 :)

To view or add a comment, sign in

More articles by Mohammad Reza Farahy

  • Six reasons that you should not use Dapr sidecar?

    1- Limitations: You will not be able to use native features of the underlying components. For example, you cannot set…

    4 Comments
  • CallerArgumentExpressionAttribute

    Tracking Caller Information You use the CallerArgumentExpressionAttribute when you want the expression passed as an…

  • Memorizer Component

    Personally, I would prefer to write everything as a component so instead of using useMemo hook you can write a…

Explore content categories