NestJs Course - part 1: Controller and Routing
Tags: node, javascript, beginners, typescript
Published: 2022-11-14 13:09:15

## Learn NestJs by creating a user management system, Part -1
While you follow along with us it's highly recommended to go through the [official documentation](https://docs.nestjs.com/).

The goal of this part: 
1. Create NestJs project
2. Create routes or controllers

Step1: Let's start by creating a project

```
$ npm i -g @nestjs/cli
$ nest new user-management-with-nestjs
```
Now, you can run go inside the project 
```
cd user-management-with-nestjs 
```
 and run the project 
```
npm run start
```


![localhost:300 preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0birp75kywm2ah63b8fc.png)

You may configure the project to listen to any other port by updating in main.ts file.
```await app.listen(<another-port>);```

---

Step 2: Now you need a route to get a list of users and to create a route you need a controller. 
You may use [CLI to generate a controller](https://docs.nestjs.com/cli/usages)
```
 nest generate controller users
```
or 
create a `users/users.controller.ts` file manually but remember need to register the controller in `app.module.ts`
```
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersController } from './users/users.controller';

@Module({
  imports: [],
  controllers: [AppController, UsersController],
  providers: [AppService],
})
export class AppModule {}

```

Presently controller file is empty and you can add decorators.
- `@Controller()` decorator to easily group a set of related routes
-  Standard HTTP methods: `@Get()`, `@Post()`, `@Put()`,  `@Patch()`, `@Delete()`, `@Options()`, and `@Head()`. In addition, `@All()` defines an endpoint that handles all of them.
- Route parameters declared in this way can be accessed using the @Param() decorator

You can try to create a rest API [CRUD](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) to create, read, update, and delete a user.

1. `@Get /users/`
2. `@Get /users/:id`
3. `@Post /users/`
4. `@Put /users/:id`
5. `@Delete /users/:id`

As you don't have a database connection yet you can begin with an array to hold the data.
```
const sampleUsers = [{
  id:1,
  name:'user1',
  email:'user1@email.com'
}]
```

simple implementation of CRUD can be as follows in `users.controller.ts` and a few more additional http methods are shown.

```
import { Controller, Delete, Get, Param, Patch, Post, Put } from '@nestjs/common';

let sampleUsers = [{
  id: 1,
  name: 'user1',
  email: 'user1@email.com'
}]
@Controller('users')
export class UsersController {
  @Get()
  findAll() {
    return sampleUsers
  }
  @Get(':id')
  findOne(@Param() params) {
    const id = params.id
    return sampleUsers.find(user => user.id === id)
  }
  @Post()
  createOne() {
    const paramsBody = {
      id: 2,
      name: 'user2',
      email: 'user2@email.com'

    }
    sampleUsers.push(paramsBody)
    return sampleUsers
  }
  @Put(':id')
  updateOne(@Param() params) {
    const id = params.id
    const paramsBody = {
      id: id,
      name: 'updatedUser',
      email: 'email-updated@email.com'
    }
    const indexOfUser = sampleUsers.findIndex(item => item.id === id)
    sampleUsers[indexOfUser] = paramsBody
    return sampleUsers[indexOfUser]
  }
  @Patch(':id')
  updateOnePartly(@Param() params) {
    const id = params.id
    const paramsBody = {
      email: 'email-update-only@email.com'
    }
    const indexOfUser = sampleUsers.findIndex(item => item.id === id)
    sampleUsers[indexOfUser].email = paramsBody.email
    return sampleUsers[indexOfUser]
  }
  @Delete(':id')
  deleteOne(@Param() params) {
    const id = params.id
    sampleUsers = sampleUsers.filter(user => user.id === id)
    return sampleUsers
  }
}
```

You can get the source code in [Github](https://github.com/sifatul/user-management-with-nestjs/tree/part-1). Like the post for part-2. 

I will be posting bi-weekly for javascript developers. Feel free to request topics that you would like to learn or recommend in the comment section.