Id validation

Here we'll improve how we validate incoming ids.

Currently, if we access the findOne() route, we can pass any kind of id and it is simply converted to number. When we have a database set up and running, it will search for it, whatever it is. However, we could validate it before this happens. And that's what we'll do now, using the power of the DTO.

Let's create a DTO to represent an id in common -> dto -> id.dto. Notice its validation, as a serial id is a positive integer.

export class IdDto {
  @IsInt()
  @IsPositive()
  readonly id: number;
}

Now, in the UsersController, we can alter the routes that receive an id, changing these occurrences

@Param('id') id: number

For this

@Param() { id }: IdDto

Now, the id is properly validated and typed, and also already extracted from the DTO. Still, all path/query params come as a string. To automatically convert the incoming id to its corresponding type in the DTO, let's add this last option in the ValidationPipe.

transformOptions: {
  enableImplicitConversion: true,
}

This will enable automatic conversion of path/query params to their corresponding primitive types. We can then remove the number conversion operator (+) from the routes, as it became unnecessary.

Commit - Applying validation

Last updated