0
0
NestJSframework~30 mins

Default value pipe in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Default Value Pipe in NestJS
📖 Scenario: You are building a simple NestJS controller to handle user queries. Sometimes users may not provide a query parameter, so you want to set a default value automatically.
🎯 Goal: Create a NestJS controller with a GET endpoint that uses the DefaultValuePipe to provide a default value for a query parameter called page.
📋 What You'll Learn
Create a controller class named AppController.
Add a GET route handler method named getItems.
Use the @Query decorator with DefaultValuePipe to set a default value of 1 for the page query parameter.
Return the page value as a number from the handler.
💡 Why This Matters
🌍 Real World
Setting default values for query parameters is common in APIs to handle missing inputs gracefully.
💼 Career
Understanding pipes like DefaultValuePipe is essential for building robust and user-friendly APIs in NestJS.
Progress0 / 4 steps
1
Create the controller class and import necessary decorators
Create a class called AppController and import Controller and Get from @nestjs/common.
NestJS
Need a hint?

Use export class AppController and decorate it with @Controller().

2
Add the GET route handler method
Inside AppController, add a method named getItems decorated with @Get() that returns 0 for now.
NestJS
Need a hint?

Define getItems() method and decorate it with @Get().

3
Import and use DefaultValuePipe for the query parameter
Import Query and DefaultValuePipe from @nestjs/common. Modify getItems to accept a page parameter from query using @Query('page', new DefaultValuePipe('1')).
NestJS
Need a hint?

Use @Query('page', new DefaultValuePipe('1')) to set default page value.

4
Convert the page parameter to a number before returning
Modify the getItems method to convert the page parameter from string to number using Number(page) and return it.
NestJS
Need a hint?

Use Number(page) to convert the string to a number before returning.