Consider this NestJS controller method:
@Get('items')
getItems(@Query('limit', new DefaultValuePipe('10')) limit: string) {
return limit;
}If a client calls /items without the limit query parameter, what will be the response?
Think about what DefaultValuePipe does when the parameter is missing.
The DefaultValuePipe provides a default value when the parameter is missing or undefined. Since limit is missing, it returns the default string "10".
Given this NestJS route handler, which option correctly applies DefaultValuePipe to the id route parameter with a default of '42'?
@Get(':id')
getById( /* what goes here? */ ) {
return id;
}Remember how to instantiate pipes and pass default values.
Option B correctly creates a new DefaultValuePipe instance with the string '42' and applies it to the 'id' parameter.
Examine this code snippet:
@Get()
getData(@Query('page', new DefaultValuePipe(1)) page: number) {
return page + 1;
}When calling /endpoint without the page query parameter, a runtime error occurs. Why?
Consider the type of the default value returned by DefaultValuePipe.
DefaultValuePipe returns the default value as-is, which is a number here, but query parameters are strings by default. The method expects a number, but the addition operation fails because the value is a string, causing a runtime error.
Consider this NestJS method:
@Get()
getItems(
@Query('limit', new DefaultValuePipe('5'), new ParseIntPipe()) limit: number
) {
return limit * 2;
}If the client calls /items without the limit parameter, what will be the output?
Think about the order pipes run and how ParseIntPipe converts strings.
DefaultValuePipe sets '5' as a string default. ParseIntPipe converts '5' to number 5. The method returns 5 * 2 = 10.
Given this method:
@Get()
getOffset(
@Query('offset', new DefaultValuePipe('0'), new ParseIntPipe()) offset: number
) {
return offset;
}If the client calls /endpoint?offset=abc, what happens?
What does ParseIntPipe do when it cannot parse a string to a number?
ParseIntPipe throws a BadRequestException if the input is not a valid number. Since 'abc' is invalid, the request fails with an error.