Getting stuck between things more then annoying - should we use middleware? [NestJS public learning #2]

Getting stuck between things more then annoying - should we use middleware? [NestJS public learning #2]

Yes...

Middleware

In this case, middleware is a function that sits between request and request handler and it can reach request and response objects as well. The NestJs middleware is pretty similar to ExpressJs middleware. The main purpose of this function is to make changes to request and response objects, however, it can do any code.

The NestJs middleware (just like the ExpressJs middleware) can end the request-response cycle if it doesn't call the next() function and here is a thing. We can chain multiple middlewares and this behavior resembles Linux piping. The previous output of the middleware will be the input of the next one.

Let's take the action

I created an enemy middleware, here is it:

First of all, I imported things (as always). The NestJs middleware is injectable just like any other provider and I needed the NestMiddleware to implement. In the import section, I imported the express request and response objects because I'm familiar with these objects.

After, we see the Enemy enum where simple letters refer to the enemy type, in this case, Monster, Soldier and Wizzard.

The NestMiddleware is implemented therefore we have to implement the use function that contains the middleware's code. The logic is simple: I get the enemy query parameter from the request and what is given to Enemy enum. If it matches with the references, it'll give back the enemy type otherwise it will be undefined. Then the result is put into the res object and we let it go with the next function.

Registration

To use our middleware, we need to register it in the module:

Here, I used a simple way. With AppModule, I implemented the NestModule therefore I can write a configure function. This function gives a lot of way to configuration and I chose the simplest one. Applying the EnemyMiddleware for every route that is controlled by HeroContorller. More detail here.

The HeroContoller

Some changes here, but not too many and I want to emphasize the main point in line 13. Our information is inside the res.locals.enemy because the middleware put it there, so we just need to use it.

If you are interested in detail the whole documentation is here.

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

Cheers.