Icad here!
Today I woke up and chose to learn a new skill: ✨NestJs✨. I decided to learn Nest because this framework is widely used besides Express and Fastify.
Learning journey objective:
Create a simple to-do list application
This article objective:
Create a dummy controller for
user
andtask
modules.
Environment:
- Windows 11
- Node version 22.2.0
- NPM version 10.8.2
- Nest CLI version 10.4.2
- Webstorm 2024.1.4
First thing first, if you don't have Nest CLI installed, you can install it using this command:
npm i -g @nestjs/cli
1. Create the Nest project
Open your command prompt, and change the direction to your project directory. Mine is D:/irsyad/project
. Then, run the command below to create a new NestJS project
nest new <your-project-name>
There will be a follow-up question to select which package manager would you prefer to use along with NestJS. I prefer to use npm.
After that, open the Nest project in your IDE. This is the structure of the Nest project
Then run the project by running this command
npm run start watch
This is the log when the Nest project successfully running
2. Create the controllers
To create a controller, we use the Nest CLI generate command. The below code is an example of generating a controller in the Nest project.
nest g controller <controller-name>
Example:
nest g controller user
This command does several things:
- Create the user module directory (if the directory doesn't exist)
- Create the user.controller.ts
- Update the app.module.ts
Next, we create the user and task controller using the command line as above.
2.1. User Controller
Inside this controller, we will create several dummy endpoints, namely:
- findAllUsers, to get all users list
- findUserById, to get user data based on id lookup
- registerUser, to add new user data
- updateUser, to update user data
- deleteUser, to delete user data from the database
// .src/user/user.controller.ts
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
@Controller('user')
export class UserController {
@Get()
findAllUsers(): string {
return 'Returning all users';
}
@Get(':id')
findUserById(@Param('id') id: string): string {
return 'Returning user with id: ' + id;
}
@Post('register')
registerUser(@Body() request: any): string {
return `Registering user with username: ${request.username}`;
}
@Put('update')
updateUser(@Body() request: any): string {
return `Update user with id: ${request.id}`;
}
@Delete('delete/:id')
deleteUser(@Param('id') id: string): string {
return 'Delete user with id: ' + id;
}
}
Explanation of the Code:
- The
@Controller('user')
decorator sets the route prefix to 'user', allowing access to the endpoints using the /user path. - The
@Get()
decorator maps thefindAllUsers()
method to a GET HTTP request, which returns a list of all users. - The
@Get(':id')
decorator maps thefindUserById()
method to a GET HTTP request with a dynamic id parameter, used to retrieve a specific user by their ID. - The
@Param('id') id: string
decorator extracts the id parameter from the URL path (/user/:id) and passes it to thefindUserById()
method as a string. - The
@Post('register')
decorator maps theregisterUser()
method to a POST HTTP request at the /user/register endpoint for user registration. - The
@Body() request: any
decorator binds the request body to the request parameter in theregisterUser()
method, allowing you to access the submitted user data. - The
@Put('update')
decorator maps theupdateUser()
method to a PUT HTTP request at the /user/update endpoint for updating user details. - The
@Delete('delete/:id')
decorator maps thedeleteUser()
method to a DELETE HTTP request with a dynamic id parameter, used to delete a specific user by their ID.
2.2. Task Controller
Similar to the user controller, the task controller will have 5 endpoints, that is:
- findAllTasks, to get all tasks list
- findTaskById, to get task data based on id lookup
- createTask, to add new task data
- updateTask, to update task data
- deleteTask, to delete task data from the database
// .src/task/task.controller.ts
import { Body, Controller, Delete, Get, Param, Post, Put } from '@nestjs/common';
@Controller('task')
export class TaskController {
@Get()
findAllTasks(): string {
return 'Returning all tasks';
}
@Get(':id')
findTaskById(@Param('id') id: string): string {
return 'Returning task with id: ' + id;
}
@Post('create')
createTask(@Body() request: any): string {
return 'Create task with data: ' + request.id;
}
@Put('update')
updateTask(@Body() request: any): string {
return 'Update task with id: ' + request.id;
}
@Delete('delete/:id')
deleteTask(@Param('id') id: string): string {
return 'Delete task with id: ' + id;
}
}
3. Test the API
I use Postman to test the input and output of the API. Let's try the APIs that have been created before.
1. /user
2. /user/update
3. /user/delete/:id
As we can see, the dummy API is successfully called and returns the output as expected. This indicates that this article will continue to the next article about creating entities and providers. See you in the next article!
Top comments (0)