#Can a `@Query` param Pipe be optional ?

1 messages · Page 1 of 1 (latest)

grand juniper
#
get(
  @Query("from", ParseIntPipe) from?: number,
  @Query("to", ParseIntPipe) to?: number,
  @Query("n", ParseIntPipe) n = 1,
  @Query("s", ParseIntPipe) s = -1,
)

This is my current function, I need all this pipes to be optional (int or undefined), is that possible ?

grand juniper
#

made a custom pipe ```ts
import { PipeTransform, Injectable, BadRequestException } from "@nestjs/common"

@Injectable()
export class ParseOptionalIntPipe
implements PipeTransform<string, number | undefined>
{
transform(value: string): number | undefined {
if (!value) return undefined
const val = Number.parseInt(value, 10)
if (Number.isNaN(val)) {
throw new BadRequestException(
"Validation failed (numeric string is expected)",
)
}
return val
}
}

trim leaf
#

You cannot mark them as optional but you can use the DefaultValuePipe for those that will have some default value

#

You could also extends the pipe and implement the optional logic by yourself instead of writing a new pipe from scratch