It doesn't hurt too much - can providers solve dependency injection? [NestJS public learning #1]

It doesn't hurt too much - can providers solve dependency injection? [NestJS public learning #1]

NestJS Provider

It is a fundamental concept of NestJS and providers provide staff - what a surprise. A lot of things can be provideable, here are some examples: service, helpers, factories etc.

So, we have a hero class and we need let's say a weapon to fight evil and ugly monsters.

Let's create the weapon service first:

Here is an interesting thing in the first line - an injectable decorator and it needs to talk about dependency injection.

Dependency injection is a design pattern and without diving too deep into this topic I try to simplify it. It is because of loose coupling and the main concept is if an object needs something another object gives that. More info in detail here.

This weapon service is pretty simple with one property and two functions. The giveWeapon sets the property and the getWeapon return the weapon. Nice and easy.

Let's see what is the situation with our hero;

It is a simple Nest controller and after importing the WeaponService we inject into through the constructor. Now, our hero can use the weapon service.

Thank's the reading. If it is useful for you push the like and don't forget to leave a comment.

Cheers.