Today, I will tell you how I refactored with routing-controllers.
routing-controllers supports @UseBefore and @UseAfter decorator for using existing middleware. but, i will change the existing middleware to class-based middleware that implemented interfaces provided by routing-controllers.
ExpressMiddlewareInterface: interface for middleware
ExpressErrorMiddlewareInterface: interface for error middleware
using auth middleware, we can check the user’s authentication status.
there are kinds of auth type, so we need to use the passport.authenticate function with the verifyCallback function. in line 11, throw an error generated by the ApiError class if the user is not authenticated.
Extending ExpressMiddlewareInterface interface of routing-controllers, create IAuthMiddleware interface for auth middleware. Then build each auth method class you want.
in the middleware.interface.ts file, we define the interface of some middleware functions. TAuthType: type of authentication. IAuthMiddleware: interface of the authentication middleware.
generate auth class for each auth type, and implement the IAuthMiddleware interface. In line 10, we define the authType property, and in line 16, we throw an error generated by the prepared HttpError class from routing-controllers if the user is not authenticated.
So far, we’ve been comparing the before and after of middleware logic.
I think it’s great for removing unnecessary utilization, interfaces, middleware, and separating logic.
It was easy to use a variety of open-source middleware that already exists for routing-controllers and also it was clear and simple to create and use custom middleware for other feature the way this library does.