DEV Community

Cover image for NestJs Course - part 1: Controller and Routing
sifatul
sifatul

Posted on • Edited on

NestJs Course - part 1: Controller and Routing

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.

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
Enter fullscreen mode Exit fullscreen mode

Now, you can run go inside the project

cd user-management-with-nestjs 
Enter fullscreen mode Exit fullscreen mode

and run the project

npm run start
Enter fullscreen mode Exit fullscreen mode

localhost:300 preview

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

 nest generate controller users
Enter fullscreen mode Exit fullscreen mode

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 {}

Enter fullscreen mode Exit fullscreen mode

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 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'
}]
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

You can get the source code in Github. 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.

Top comments (0)