NestJS: Clean Code With Decorators

What is a Decorator?

TL;DR Decorator is a sort of declaration that can be used changing behaviour of a property or adding meta data to a class/property/method or extending functionality of a method etc.
In short, a function applied with prefix @ that gets automatically executed at runtime.

@Min(18)
public age: number;

Premise

In one of our recent projects, I had to apply concurrency lock on an existing method. Distributed shared lock is pretty easy and achievable in many ways. I chose Redis andSETNX command for this purpose.

  1. Call the acquireLock() at the very beginning of the method.
  2. Wrap the entire existing method code in try/catch
  3. Call the releaseLock() in finally block

Disadvantage Of Above Code Style

The above code looks pretty messy and cumbersome every time any existing method needed to be wrapped with concurrency lock.

End Goal

The goal is to get rid of the above three common steps required every time we need locking.

Implementation Of @ConcurrencyLock() decorator

We can achieve the above goal easily with Method Decorator. Let’s have a look into the code.

Explanation

I am not going to explain line by line. I believe, little javascript/typescript learning would suffice to understand the code easily.

Line 12: const LockServiceinjector = Inject(LockService);
Line 19: LockServiceinjector(target, 'lockService');
Line 22: descriptor.value = async function wrapper(...args: any[])...

Conclusion

Don’t overlook decorators. They are cool building blocks to work with. Don’t confine yourself using the only decorators provided by the framework out of the box, better off, code your own decorators.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
LiftOff LLC

LiftOff LLC

We are business accelerator working with startups / entrepreneurs in building the product & launching the companies.