#Params Validation, type error

11 messages · Page 1 of 1 (latest)

steep jungle
#

Hi,
I'm new to nestjs and I am trying to make params validation for uuid.

I should do some conversion between the step of validation and usage of my uuid here ?

For now, I cannot use the id because find() operator doesn't accept my UserIdParams Object which is a string

Error message

Type 'UserIdParams' is not assignable to type 'string | FindOperator<string>'.

users.dto.ts

export class UserIdParams {

  @IsNotEmpty()
  @IsUUID()
  readonly id: string;

}

users.controller.ts

  @Get(':id')
  @UsePipes(new ValidationPipe({ transform: true }))
  async findById(@Param('id') id: UserIdParams): Promise<User> {
    return this.userService.findById(id);
  }

users.service.ts

  async findById(id: UserIdParams): Promise<User> {
    const user = await this.usersRepository.findOneBy({ id });   //  <-------- Error Here

    if (!user) {
      response.statusCode = HttpStatus.BAD_REQUEST;
      throw new HttpException({ message: 'User not found' }, HttpStatus.BAD_REQUEST);
    }

    try {
      return user;
    } catch (error) {
      throw new HttpException({ message: 'Error finding user' }, HttpStatus.INTERNAL_SERVER_ERROR);
    }

  }
keen stirrup
#

The UserIdParams is not a string, it's the type of the whole params object.

#

The Param('id') decorator extracts only the id property of the Params object, but it doesn't check that the actual typescript type is correct (which it is not).

#

You have 2 options here - either use @Param('id') id: string, because the id property is actually a string (but in this case the validation pipe would not trigger).
Or, use @Param() params: UserIdParams, which will assign the whole UserIdParams object to the params property and also trigger the validation pipe.

If you want only the id property, you can alo use parameter destructuring @Param() { id }: UserIdParams

#

Another option is to use the ParseUUIDPipe instead of using the class validator.
@Param('id', ParseUUIDPipe) id: string

steep jungle
#

Little question, I am making double validation using pipe and this snippet ?

    const errors = await validate(id);
    if (errors.length > 0)
      throw new HttpException(errors, HttpStatus.BAD_REQUEST);

keen stirrup
#

Yeah, if you use a pipe to validate your input, then doing it again manually is unnecessary

steep jungle
#

this seems to work just fine

#

it is the recommended way ?

timber forge