adetoola
adetoola

Reputation: 716

Nestjs - Routes defined within controllers are overriding each other

I have a controller

//imports etc
...

@Get('me')
async get(@Req res): Promise<UserVm> {
    // extract auth user from request object
    // return auth user
}

@Get(':id') // uuid
async get(@Param('id') id: string): Promise<UserSummaryVm> {
    // return a summary user profile
}
...

Howvever, the /:id is overriding the /me. I have tried reorder the routes to no avail. I always get the following error:

[Nest] 94764   - 8/23/2018, 7:45:50 PM   [ExceptionsHandler] Could not find 
any entity of type "User" matching: "me"
EntityNotFound: Could not find any entity of type "User" matching: "me"
at new EntityNotFoundError
([PROJECT_ROOT]\src\error\EntityNotFoundError.ts:11:9)
at [PROJECT_ROOT]\src\entity-manager\EntityManager.ts:622:39
at process._tickCallback (internal/process/next_tick.js:68:7)

How do i resolve this? Any hint or pointer is appreciated.

Upvotes: 2

Views: 3671

Answers (1)

Mahdi Imani
Mahdi Imani

Reputation: 204

By default all API-Endpoint show with this standard:

GET    ../user      =>  [user1, user2, user3]
GET    ../user/1    =>  user1
PUT    ../user/1    =>  user1(that updated)
DELETE ../user/1    =>  user1(that deleted)

SOLUTION A

that means regular pattern must follow this order, but for new situation or case like your it can use other method like:

GET  ../user       =>  [user1, user2, user3] all user
GET  ../user/id/1  =>  user1
GET  ../user/me    =>  userX

SOLUTION B

change the position of method in class may have effect on your response.

@Get(':id')
async get(@Param('id') id: string): Promise<UserSummaryVm> {
    if ( !Number.isInteger(id) ) next();
    ...
}

@Get('me')
async get(@Req res): Promise<UserVm> {
    ...
}

In this arranging, all request checked, if they have number in URL like id that to be absorbed by @Param('id') id: string execute firstly and then if there is no number in request parameter goes further.

 if ( !Number.isInteger(id) ) next();

If statement change the role and goes to next middleware if input parameter was not INTEGER.

Upvotes: 7

Related Questions