Using middlewares in Tupã is easy. We can implement middlewares both at the route level, sets of routes and global middlewares.
Simple Middlewares
Let’s add a simple middleware at the route level. Just add a new Middlewares property inside the endpoint object.
Let’s add a middleware to the /cats route.
We can obtain the result of the above middleware, just press F12 and check the request in the Network tab of our devtools.
Different Middlewares for Sets of Routes
But it may be that we want to add different middlewares for different sets of routes. In this case, we can store our routes in functions and call the GetRoutes() method from Tupã as a parameter to the RegisterRoutes() function. See an example below:
Middlewares in Sets of Routes + Specific Routes
We can also add middlewares for sets of routes and specific routes together. In this case, the order will be that the specific route middlewares will take precedence over the group ones in execution. Let’s see in the following code:
Output:
However, in some cases, we will need to store some data after any request is completed and after all sets of AfterMiddlewares. For this, we should use the Global Middlewares.