NestJS study notes

brief introduction

Nest is a framework for building Node.js server-side applications. It uses progressive JavaScript, built-in TypeScript (but allows code to be written in pure JavaScript), and combines the elements and ideas of OOP (object-oriented programming), FP (functional programming) and FRP (functional response programming). Many of the design inspiration comes from Angular.
Many patterns of Angular come from the Spring framework in Java, such as dependency injection and aspect oriented programming, so you can think that Nest is the Spring framework of Node.js.

Comparison of frames of the same type

  • Midway
  • Egg
  • Express

install

Related commands

#Installation of scaffold
$ npm i -g @nestjs/cli

#Create a project using scaffolding
$ nest new [project-name]

#Default start project command
$ npm run start

#Package project
$ nest run build

Scaffold initialization project - Options

- Which package manager would you to use?(Select the package manager you want to use)
  yarn | npm(default) | pnpm

Initial directory structure

src
 ├── app.controller.spec.ts  Unit test example for basic controller
 ├── app.controller.ts  Example of a basic controller with a single route
 ├── app.module.ts Application root module
 ├── app.service.ts Basic service provider with a single method
 └── main.ts Application entry file

Other instructions

#View help options
$ nest --help|-h

#Automatically create a controller module file named [module name] in the directory
$ nest generate|g co [module-name]

#Show project information
$ nest info

#Update dependent packages
$ nest update|u

#Add dependent package
$ nest add [library-name]
Generate command description (click to view):
name alias explain
application application Generate a new application workspace
class cl Generate a new class
configuration config Generate CLI configuration file
controller co Generate and declare a controller module
decorator d Generate custom decorator
filter f Generate and declare a filter module
gateway ga Generate and declare a gateway module
guard gu Generate and declare a rights guard module
interceptor in Generate and declare an interceptor module
interface interface Generate and declare an interface definition module
middleware mi Generate and declare a middleware module
module mo Generate and declare a module management file
pipe pi Generate and declare a pipe model provider
resolver r Generate and declare a GraphQL parser module
service s Generate and declare a service module
library lib Generate new libraries in monorepo
sub-app app Generate new applications in monorepo
resource res Generate a new CRUD resource

Module overview

Controller

Generally speaking, it is a routing Router, which is responsible for processing the request parameters passed in by the client and returning the response data to the client. It can also be understood as the logical processing of HTTP requests.

Note: to create a controller class using the CLI, simply execute the $nest g co [name] command.

Example:

//dto/create-cat.dto.ts

//Define a Dto class to specify the format of parameters that should be passed in.
export class CreateCatDto {
  readonly name: string;
  readonly age: number;
  readonly breed: string;
}


/* cats.controller.ts */

import { Controller, Get, Query, Post, Body, Put, Param, Delete } from '@nestjs/common';
import { CreateCatDto, UpdateCatDto, ListAllEntities } from './dto';

@Controller('cats') //A routing prefix named "cats" is defined
export class CatsController {
  @Post() //Access the "/ cats /" route through the Post method
  create(@Body() createCatDto: CreateCatDto) {
    return 'This route will add a new piece of data';
  }

  @Get() //Access the "/ cats /" route through the Get method
  findAll(@Query() query: ListAllEntities) {
    return `This route will return all data (limit: ${query.limit} items)`;
  }

  @Get(':id') //Access the "/ cats/${id}" route through the Get method
  findOne(@Param('id') id: string) {
    return `This route will be based on ${id}Returns the specified data`;
  }

  @Put(':id') //Access the "/ cats/${id}" route through the Put method
  update(@Param('id') id: string, @Body() updateCatDto: UpdateCatDto) {
    return `This route will be based on ${id}Update specified data`;
  }

  @Delete(':id') //Access the "/ cats/${id}" route through the Delete method
  remove(@Param('id') id: string) { //delete reserves the keyword for js and can be named with remove
    return `This route will be based on ${id}Delete specified entry`;
  }
}

Providers

Providers is a class annotated with the @ Injectable() decorator. Many basic Nest classes may be regarded as provider s, such as service, repository, factory, helper, etc., and inject dependencies through the constructor (constructor).

Note: to create a service class using the CLI, simply execute the $nest g s [name] command.

The most common is to use the @ Injectable() decorator to create a class that provides data operation services, that is, the service module.
Example:

//interfaces/cat.interface.ts
export interface Cat {
  name: string;
  age: number;
  breed: string;
}


//cats.service.ts
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';

@Injectable()
export class CatsService {
  private readonly cats: Cat[] = [];

  create(cat: Cat) {
    this.cats.push(cat);
  }

  findAll(): Cat[] {
    return this.cats;
  }
}

Then use it in CatsController:

//dto/create-cat.dto.ts
export class CreateCatDto {
  readonly name: string;
  readonly age: number;
  readonly breed: string;
}


//cats.controller.ts
import { Controller, Get, Post, Body } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
import { CatsService } from './cats.service';
import { Cat } from './interfaces/cat.interface';

@Controller('cats')
export class CatsController {
  constructor(private catsService: CatsService) {}

  @Post()
  async create(@Body() createCatDto: CreateCatDto) {
    this.catsService.create(createCatDto);
  }

  @Get()
  async findAll(): Promise<Cat[]> {
    return this.catsService.findAll();
  }
}

After defining the service module (provider) and controller routing module (consumer), you also need to register in the module management file.
Example:

//app.module.ts
import { Module } from '@nestjs/common';
import { CatsController } from './cats/cats.controller';
import { CatsService } from './cats/cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class AppModule {}

Then we have the current directory structure:

src
├── cats
│    ├──dto
│    │   └──create-cat.dto.ts
│    ├── interfaces
│    │       └──cat.interface.ts
│    ├──cats.service.ts
│    └──cats.controller.ts
├──app.module.ts
└──main.ts

Module

Unfinished to be continued...

Tags: Javascript node.js Front-end Back-end

Posted on Fri, 03 Dec 2021 03:29:47 -0500 by anand_ragav