#Can I prevent mismatch of a Nest route pattern and its param DTO before run-time?

6 messages · Page 1 of 1 (latest)

split dirge
#

Consider the following route in a controller:

@Get('/:uuid')
findById(@Param() params: FindProjectParamsDto): Promise<Project> {
    return this.projectsService.findById(params);
}

Let's say that FindProjectParamsDto is defined like this:

export class FindProjectParamsDto extends PickType(ProjectDto, [
  'id',
] as const) {}

(or is not mapped, but just contains the id property). Let's also say that this property also has validators like @IsNotEmpty() or @IsUUID().

You can easily spot a problem here: on a request, the extracted route param is uuid, while params is supposed to have id, hence id is empty. Such a request always fails as validators cause a response like:

{
  "statusCode": 400,
  "message": [
    "id must be a UUID",
    "id should not be empty"
  ],
  "error": "Bad Request"
}

I wonder if such a problem can be automatically prevented via a static code analyser. Obviously, TypeScript itself doesn't spot this as it doesn't care about the route string content. But may be there's already a standart solution to this for Nest?

May be a standart autotest that takes the DTO, populates values in the route using validators and/or examples (from @ApiProperty), passes it to the controller and checks that it doesn't invalidate it? (because "/:uuid" after substituting ":id" with a valid value will still be "/:uuid" and hence the test will fail) Such a test will give false negative results, though: "/:isGoodEnough" with isGood in DTO will probably give something like { isGood: "trueEnough" }, but this is obviously better than no validation (in the end, if isGood has @IsBooleanString(), { isGood: "trueEnough" } won't pass).

Note: an autotest approach would be good enough if it can be applied to all routes at once; writing a specific autotest per route is way too much of an overhead.

#

Can I prevent mismatch of a Nest route pattern and its param DTO before run-time?

pale glade
#

I think so
but you'd have implement this yourself

split dirge
pale glade
#

I´d try to do that as an eslint rule