How to implement a decorator design pattern in NodeJS

Melik Karapetyan
2 min readJan 31, 2020

--

Yesterday I came across to a problem when the decorator design pattern was really needed, but NodeJS does not support it natively. I’ve decided to implement my own and share it with you. Let’s start.

The problem

There is one single backend that has multiple clients each of them can make a request to the backend and receive a response. Writing each request handler for every client is a headache and can cause a lot of duplicate code because the data is almost the same except the format. For example, we have web applications and mobile applications that request user profile and they expect data in different formats that are suitable for their needs.

Solution

With the help of a decorator design pattern, one can have a complete implementation for one specific client and transform that response into a response for the other clients using decorators.

Here, with the help of decorate function one can decorate any method within any object. The last argument of the function is the object to which the method belongs, in case of classes, it is this.

The object_path is simply the path of the function starting from the object using dot notation.

The method is the new function which we want to call either before or after the original function. And finally, the pos argument defines whether we want to decorate before or after.

The output from the snippet before will be the following

@DecoratorBefore3 with argument Test Data
@DecoratorBefore2 with argument Test Data
@DecoratorBefore1 with argument Test Data
Call of original Method with argument Test Data
@DecoratorAfter1 with argument Test Data
@DecoratorAfter2 with argument Test Data
@DecoratorAfter3 with argument Test Data

Here we decorated the log function which is the property of Bar class withing Foo class object.

That’s it. Hope it helped. Thank you for your time.

--

--