Is there a nice-looking way to create overloaded routes in NestJS application? I have some thoughts, but maybe I'm inventing a wheel. I couldn't find any ready approach though...
What I'm talking about is something like this (lets take https://github.com/nestjs/nest/blob/master/sample/01-cats-app/src/cats/cats.controller.ts as start point):
@Get()
async findAll(): Promise<Cat[]> {
return this.catsService.findAll();
}
@Get()
@Roles('admin')
async findAllAdmin(): Promise<Cat[]> {
return this.catsService.findAllAdmin();
}
In other words, I want have two routes with same URL, but distinguished by some other values (like role here).
My idea was to create my own decorator, instead of Get, which will fill some weight map, assign to each overloaded method unique path. And then, add middleware, which will get parameters from request, compare them against map, and do internal redirect (with next('route')
or req.app.handle(req, res)
) to appropriate new path.
But in that approach I couldn't get user from request, if they should be authenticated with AuthGuard on one of methods...
if
branch in your controller that calls different service methods – Jesse Carterif
branch in each of them looks like a lot of boilerplate to me... Also, methods could have different parameters, for example, imagine@UserAccount() account: Account
parameter decorator, which will inject user's account in user-related method, but could fail on system admin role, in admin-related method. – yumaa