Performance: Default value pipe
This affects the server response time by handling missing or undefined input values efficiently before controller logic runs.
async getUser(@Query('page', new DefaultValuePipe(1)) page: number) { // page is guaranteed to have a value // rest of logic }
async getUser(@Query('page') page: number) { if (page === undefined) { page = 1; } // rest of logic }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual default assignment in controller | N/A | N/A | N/A | [OK] |
| Using DefaultValuePipe for defaults | N/A | N/A | N/A | [OK] Good |
DefaultValuePipe in NestJS?DefaultValuePipe to set a default value of 10 for a query parameter named page?new keyword and passed as the second argument to decorators like @Query.new DefaultValuePipe(10) is correct.new DefaultValuePipe(value) with decorator [OK]limit if the request URL is /items (no query parameters)?
@Get('items')
getItems(@Query('limit', new DefaultValuePipe(5)) limit: number) {
return limit;
}/items has no limit query parameter provided.limit is missing, DefaultValuePipe sets it to the default value 5.DefaultValuePipe:
@Get('users')
getUsers(@Query('page', DefaultValuePipe(1)) page: number) {
return page;
}new keyword, but here it is called like a function.sort query parameter with a default value of 'asc'. Additionally, if the client sends an empty string for sort, it should also default to 'asc'. Which approach correctly achieves this behavior?@Query('sort', new DefaultValuePipe('asc')) sort: string = 'asc' sets default but does not handle empty string; Use @Query('sort', new DefaultValuePipe('asc')) sort: string does not handle empty string; Use @Query('sort') sort: string = 'asc' without any pipe ignores pipe usage.Pass the test and this pattern moves unknown