Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nestjs Validation failed (numeric string is expected) inside controller's nested route

Tags:

nestjs

I have a controller using @Controller('tasks') decorator. Inside this controller, I have a route @Get('/week'), normally the request should go localhost:4000/tasks/week but it is returning a bad request:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Validation failed (numeric string is expected)"
}

Below is my code:

@Controller('tasks')
@UseGuards(AuthGuard())
export class TasksController {
  constructor(private tasksService: TasksService) { }

  @Get('/:id')
  getTaskById(@Param('id', ParseIntPipe) id: number): Promise<Task> {
    return this.tasksService.getTaskById(id);
  }

  @Get('/week')
  getTasksByWeek(@GetUser() user: User): Promise<Task[]> {
    return this.tasksService.getTasksByWeek(user);
}

Removing the /week from Get() decorator works but not adding it.

Expected result: return data

Actual result:

 {
    "statusCode": 400,
    "error": "Bad Request",
    "message": "Validation failed (numeric string is expected)"
}
like image 678
J.D Avatar asked Mar 18 '26 20:03

J.D


2 Answers

As answers given are not really explaining the "why" of this behaviour, here's a quick explanation:

It's just a matter of ordering and what route is met First: "week" is mistaken with an ":id", like 123, 204...etc.

As your router tries the first route that meet route requirements (pattern in this case), your request is forwarded to /id route. It happens in every http framework with a router.

Validation occurs later on. So in short, the only thing that matters in route selection, is pattern, not validation set in it.

This ordering is really important, as you'll face same exact issue in all major http framework with a router.

like image 167
millenion Avatar answered Mar 23 '26 04:03

millenion


I found a fix for this issue. Routes such as Get('week') or routes that accept parameters should be lined before routes with base controller route.

Assume we have a route @GET() like below that gets all the tasks:

 @Get()
  getTasks(@GetUser() user: User): Promise<Task[]> {
    return this.tasksService.getTasksByWeek(user);
}

How it should be in the code:

@Controller('tasks')
@UseGuards(AuthGuard())
export class TasksController {
  constructor(private tasksService: TasksService) { }

  @Get('/:id')
  getTaskById(@Param('id', ParseIntPipe) id: number): Promise<Task> {
    return this.tasksService.getTaskById(id);
  }

  @Get('/week')
  getTasksByWeek(@GetUser() user: User): Promise<Task[]> {
    return this.tasksService.getTasksByWeek(user);
}
 @Get()
  getTasks(@GetUser() user: User): Promise<Task[]> {
    return this.tasksService.getTasksByWeek(user);
}
like image 33
J.D Avatar answered Mar 23 '26 03:03

J.D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!