Dec 4, 2019· 8 mins to read

Building Modern Nodejs Application using Nestjs and TypeScript


Building Modern Nodejs Application using Nestjs and TypeScript

In this article, we will see how to build REST API using Nestjs with TypeScript. Building Modern Nodejs Application using Nestjs and TypeScript

Recent Articles,

How to Run MongoDB as a Docker Container in Development

TypeScript Basics – The Definitive Guide

Crafting multi-stage builds with Docker in Node.js

Nestjs is a framework for building efficient,scalable node.js server side applications.

Under the hood, Nest makes use of robust HTTP Server frameworks like Express (the default) and optionally can be configured to use Fastify as well!

Why NestJS

Nest provides an out-of-the-box application architecture which allows developers and teams to create highly testable, scalable, loosely coupled, and easily maintainable applications.

it provides design patterns out-of-the-box which helps to develop scalable application.

Resources

Here, i will mention some of the good resources that you can follow to get deep dive into nestjs

Setting up NestJS

First install nestjs globally on your machine to use the nestjs cli in your machine.

npm i -g @nestjs/cli

now, you can able to use nest command globally. After that, you can create a new nestjs project using the command.

nest new rest-nest-api

it will create a project scaffold. it will create lot of files for us to save time.

  • scaffold

Project Structure

  • project structure

there are bunch of files that are predefined here. let’s try understand one by one.

First and foremost, you can see a file main.ts in the application. it is a main entrypoint for an application.

import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();

it will take the file app.module and create server instance by calling NestFactory.create and start running server on PORT 3000. we can change the port if we want to.

Module

After that, app.module.ts. it will contains the group of components such as controller,services for the particular domain.

For Example, if we are designing REST API to handle User, User controller and User Service will be grouped in the user.module.ts and will be used in all other places.

app.module.ts will contain the App Controller and App Service

import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";

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

Controller

Controller handles all the request and response and Service will have all the interaction between DB and controller.

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}

AppController will have decorator @Controller based on that nestjs identifies the controller and services.

we have method called @Get decorator which tells that it is a get method. if you pass the prefix in the @Controller,it will handle that particular route.

For example, if you want to handle the /user routes in the UserController, you can pass ’user’ in the controller like @Controller(‘user).

Each method decorator such as @Get,@Post and @Put in UserController will be added with a prefix.

Services

Services will be injected to the controller. Service contains all the Database queries.

import { Injectable } from "@nestjs/common";

@Injectable()
export class AppService {
  getHello(): string {
    return "Hello World!";
  }
}

let’s run the application. To run it, we can use the command

npm run start:dev

you can see the application running in terminal like

  • run

you can visit the url http://localhost:3000

  • op

Let’s Build Some REST API

Let’s create a CRUD for todo application in nestjs. Before starting to create a api for a domain, remember the flow of nest js.

nestjs

Firstly, create a service for todo domain. you can generate the service using the following command,

nest generate service todos

service command

After that, create a controller file using the following command,

nest generate controller todos

controller command

Once those files are created, it will be added into app.module.ts automatically.

app module

Now, it is time to write some API for our application. To get all the todos data, we need a get request.

First create a get method in the todos.service.ts

todos = [{ id: 1, name: 'Complete' }, { id: 2, name: 'Check' }];

getTodos() {
    return this.todos;
  }

Once you add the function in service, import service in the controller to use that function.

constructor(private todosService: TodosService) {}

Now, you can able to call the get method in the controller

@Get()
  getTodos() {
    return this.todosService.getTodos();
  }

it will return all the todos in the get request. you can verify it by running the application.

get api

Likewise, we will add the other api request such as POST,PUT and DELETE.

todos.controller.ts

import {
  Controller,
  Get,
  Param,
  Post,
  Body,
  Put,
  Delete,
} from '@nestjs/common';
import { TodosService } from './todos.service';

interface todosDto {
  id: string;
  name: string;
}

@Controller('todos')
export class TodosController {
  constructor(private todosService: TodosService) {}

  @Get()
  getTodos() {
    return this.todosService.getTodos();
  }

  @Get(':id')
  getTodo(@Param() params) {
    console.log('id', params.id);
    return this.todosService.getTodos().filter(t => t.id === params.id);
  }

  @Post()
  addTodo(@Body() todo: todosDto) {
    console.log('todo', todo);
    this.todosService.addTodo(todo);
  }

  @Put()
  updateTodo(@Body() todo: todosDto) {
    console.log('update todo', todo);
    this.todosService.updateTodo(todo);
  }

  @Delete()
  deleteTodo(@Body() todo: todosDto) {
    console.log('delete todo', todo.id);
    this.todosService.deleteProduct(todo.id);
  }
}

todos.service.ts

import { Injectable } from "@nestjs/common";

@Injectable()
export class TodosService {
  todos = [
    { id: 1, name: "Complete" },
    { id: 2, name: "Check" },
  ];
  getTodos() {
    return this.todos;
  }

  addTodo(todo) {
    this.todos = [...this.todos, { ...todo }];
  }

  updateTodo(todo) {
    this.todos = this.todos.map((t) => {
      if (t.id == todo.id) {
        return { ...todo };
      }
      return t;
    });
  }

  deleteProduct(id) {
    this.todos = this.todos.filter((t) => t.id != id);
  }
}

After adding the following code, we can able to add todo and update it using the api’s. you may noticed that i used interface in the controller.

NestJs uses interface to model the data use to check the type of data in the POST Body and other places also.

Basically, it is a common pattern that is used in Nestjs Application development

post

get api's updated

Summary

To conclude, this summarizes the basic concepts to run the Nestjs application and Building Modern Nodejs Application using Nestjs and TypeScript .

we will see some advanced concepts of Nestjs in upcoming articles.

Recommended Course to Learn TypeScript : Stephen grider’s TypeScript Course

Copyright © Cloudnweb. All rights reserved.