Easy flow, easy reach - what can we do with pipes?[NestJS public learning #3]

Easy flow, easy reach - what can we do with pipes?[NestJS public learning #3]

NestJs Pipes

Pipes are tricky things here, in my view. These things work with route handler arguments but a pipe is called before the controller. It does two things, transformation and validation. After this operation, the pipe gives the (optionally) changed or validated values for the controller. In case of validation, if the value is not valid the pipe throws an error.

NestJs has a bunch of validation pipes but we can write our own. It is true for transformation pipes as well and I created one. Let's check it!

Fire damage

I wanted to create a fire damage pipe that decreases the hit points by 10. It looks like:

Every custom-designed pipe has to implement PipeTransform which contains the transform function therefore it is needed to implement.

The transform function assumes the value and metadata (which is not used here for this reason it is a low-dash now)

The value contains the hp and in a try-catch block we return with hp minus 10. If any error occurs the catch block throws a bad request exception. Nice and simple.

The hero gets fire damage

How to consume our pipe? Here is the way:

Inside the Hero controller, I created a new route handler with /firedamage/:hp path and this way we can give the hit points in the URL. It is not necessary I just wanted this design.

Inside the param decorator, the fire damage pipe is instantiated therefore it gets the hp param before the route handler and after the transformation, this gives the modified hp.

Let's call the route:

and the result:

You can see the hit points decreased by 10 as we planned before.

You can ask - why should we use pipe when we can reach the same result with middleware? Yep, it is true but there is a big difference. The middleware reaches the request object and it has no clue about execution context. Pipe has.

More detail in the documentation.

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

Cheers.