Skip to content

Commit 2e8b9c5

Browse files
Merge pull request #1200 from apatryda/1199-default-value-pipe-docs
docs(common): add DefaultValuePipe docs
2 parents f9910d5 + 74c3d93 commit 2e8b9c5

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

content/pipes.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ Nest comes with five pipes available out-of-the-box:
2424
- `ParseBoolPipe`
2525
- `ParseArrayPipe`
2626
- `ParseUUIDPipe`
27+
- `DefaultValuePipe`
2728

2829
They're exported from the `@nestjs/common` package. In order to better understand how they work, let's build `ValidationPipe` and `ParseIntPipe` from scratch.
2930

@@ -443,6 +444,21 @@ findOne(userEntity) {
443444

444445
We leave the implementation of this pipe to the reader, but note that like all other transformation pipes, it receives an input value (an `id`) and returns an output value (a `UserEntity` object). This can make your code more declarative and [DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) by abstracting boilerplate code out of your handler and into a common pipe.
445446

447+
#### Providing defaults
448+
449+
`Parse*` pipes expect a parameter's value to be defined. They throw an exception upon receiving `null` or `undefined` values. To allow an endpoint to accept parameter absence in queries we have to provide a default value which would get injected before `Parse*` pipes operate on these values. The `DefaultValuePipe` was introduced into Nest for that purpose.
450+
451+
```typescript
452+
@@filename()
453+
@Get()
454+
async findAll(
455+
@Query('activeOnly', new DefaultValuePipe(false), ParseBoolPipe) activeOnly: boolean,
456+
@Query('page', new DefaultValuePipe(0), ParseIntPipe) page: number,
457+
) {
458+
return this.catsService.findAll({ activeOnly, page });
459+
}
460+
```
461+
446462
#### The built-in ValidationPipe
447463

448464
Fortunately, you don't have to build these pipes on your own since the `ValidationPipe` (along with `ParseIntPipe`, `ParseBoolPipe`, `ParseArrayPipe` and `ParseUUIDPipe`) are provided by Nest out-of-the-box. The built-in `ValidationPipe` offers more options than in the sample we built in this chapter, which has been kept basic for the sake of illustrating the basic mechanics of a pipe. You can find full details, along with lots of examples [here](/techniques/validation).

0 commit comments

Comments
 (0)