introduce

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, has built-in and full TypeScript support (but still allows developers to write code in pure JavaScript), and combines elements of OOP (object-oriented programming), FP (functional programming), and FRP (functional response programming).

Copy and reference to NestJs Chinese document

PS1: NestJs Chinese website

The installation

As with Vue, you can build a Nest project using scaffolding, or clone the source code directly from Git. NestJs scaffolding is recommended here… Because it’s easier

# npm
npm i -g @nestjs/cli

# yarn
yarn global add @nestjs/cli
Copy the code

PS2: Rely on Node.js (ver>=10.13.0)

Create a project

nest new project-name
Copy the code

Select YARN

Create successfully, open folder to have a look, the project structure is as follows

SRC ├ ─ ─ app. Controller. Spec. Ts ├ ─ ─ app. The controller. The ts ├ ─ ─ app. The module. The ts ├ ─ ─ app. Service. The ts └ ─ ─ the main, tsCopy the code

Looking at this structure, I believe that some of you who have done Java, especially the Spring framework, are already getting excited. Don’t worry, more exciting content is still to come

PS3: SONY’s third generation home video game console

Start the

Open the main ts

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  / / 3000 - > 8081
}
bootstrap();
Copy the code

Change the default listening port to 8081,3000 for Vue to use

Then run YARN start:dev to start in development mode

Visit localhost:8081, or use Postman to request it

So, Hello World! How does it come back.

Let’s open up the code for the controller and take a look

// app.controller.ts

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

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

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

As you can see, the AppService class is referenced and instantiated, and its getHello method is called and returned. Let’s take a look at the service code

// app.service.ts

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

@Injectable(a)export class AppService {
  getHello(): string {
    return 'Hello World! '; }}Copy the code

In this way, the structure is very clear. As for these decorators beginning with @ in the code, they will be introduced later. You can look at the Chinese document, but I won’t introduce them in detail here.

To test the conjecture, let’s change the return value of getHello() to ‘Hello Nest’ and try it out.

PS4: If the project is started in development mode yarn Start :dev, you do not need to restart the project when you modify the code of non-configuration items. If you directly start the project using YARN Start, you need to restart the project every time you modify the code.

New Function modules

As we know above, the project structure of NestJs is composed of three main parts, Controller, Service and Module, which together form a Module.

  • Controller: indicates that the Controller passes@Controller()Decorator class defined to receive application-specific requests. The routing mechanism controls which controller receives which requests. Typically, each controller has multiple routes, and different routes can perform different operations. It functions like Spring, mainly providing apis for the front end and some simple validation.
  • Service: The Provider, also called Provider, passes@Injectable()The classes defined by the decorator, which also function like Spring’s service layer, are responsible for handling the specific business, where the logical code is generally written.
  • Module: indicates that the Module is passed@Module()The class defined by the decorator, which is different from Spring, is mainly responsible for wiringControllerandServiceSomething like thatnamespace.

Now, let’s add a module for logging in to the service to try it out.

To see the nest command list, type nest-h

Options:
  -v, --version                                   Output the current version.
  -h, --help                                      Output usage information.

Commands:
  new|n [options] [name]                          Generate Nest application.
  build [options] [app]                           Build Nest application.
  start [options] [app]                           Run Nest application.
  info|i                                          Display Nest project details.
  update|u [options]                              Update Nest dependencies.
  add [options] <library>                         Adds support foran external library to your project. generate|g [options] <schematic> [name] [path] Generate a Nest element. Available Schematics, ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┬ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │ name │alias│ description │ application │ application │ Generate a new application workspace │ class │ cl │ Generate a new class │ │ configuration │ config │ Generate a CLI configuration file │ controller │ co │ Generate a controller declaration │ │ Generate a custom decorator │ │ filter │ f │ Generate a filter declaration │ gateway │ ga │ Generate a gateway declaration │ guard │ gu │ Generate a guard declaration │ interceptor │in│ Generate an interceptor declaration │ interface │ interface │ Generate an interface │ middleware │ mi │ Generate a Middleware declaration │ │ module │ mo │ Generate a module declaration │ pipe │ PI │ Generate a pipe declaration │ Provider │ pr │ Generate a provider declaration │ resolver │ r │ Generate a GraphQL resolver declaration │ service │ S │ Generate a service declaration │ library │ lib │ Generate a new library within a monorepo │ sub-app │ app │ Generate a new application within a monorepo │ resource │ res │ Generate a new CRUD resource │ └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┴ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘Copy the code

Create a module

Module

Use Generate to create a new module

nest g mo user system
Copy the code

The aliases and descriptions of each command are given in the help list above. The meaning of the above command is to generate a module named login under system. Then let’s look at the project structure.

As you can see, the corresponding path and file have been generated, of course, only Module is definitely useless, let’s create the Controller. Also use scaffolding to generate

Controller

# Controller
nest g co user system
Copy the code

Open the user. The module. Ts

// user.module.ts

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';

@Module({
  controllers: [UserController],
})
export class UserModule {}
Copy the code

Open the app. The module. Ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UserModule } from './system/user/user.module';

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

As you can see, the new Controller has been automatically introduced, and the new module has been automatically introduced, very smart (fool?). .

Service

# Service
nest g s user system
Copy the code

Again, the generated Service is automatically imported and does not need to be manually configured

Add an interface

Let’s start by adding a registration interface to the user controller

import { Controller, Post } from '@nestjs/common';

@Controller('user')
export class UserController {
  @Post('register')
  register() {
    return true; }}Copy the code

Test the

  • Local route prefix

This introduces the concept of routing. As you can see from the code, the @controller decorator is automatically filled with a user in the generated user module, opening the definition of @controller ()

export declare function Controller(prefix: string | string[]) :ClassDecorator;
Copy the code

@post () defines a Post request interface with path /register, so if we want to locate a method on a controller, we need to access the controller prefix + method prefix.

  • Global route prefix

Since it is global, you must set the global route in the entry file, using app.setGlobalPrefix() in main.ts

// main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('api');
  await app.listen(8081);
}
Copy the code

Let’s test it out

To add logic, test the input parameter

  • user.controller.ts
import { Body, Controller, Post } from '@nestjs/common';
import { UserService } from './user.service';

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Post('register')
  // @body () helps get the parameters in request.body
  register(@Body() user: any) {
    return this.userService.register(user); }}Copy the code
  • user.service.ts
import { Injectable } from '@nestjs/common';

@Injectable(a)export class UserService {
  register(user: any) :boolean {
    // Let's see if the parameters are successfully received
    console.log(user);
    if(user? .userName && user? .pwd && user? .pwd === user? .confirmPwd) {return true;
    } else {
      return false; }}}Copy the code

PS5: Because this is test logic, there is no type constraint (anyScript is the best!). Type constraints must be perfected in actual development. It will bring great help to our subsequent development and maintenance

  • Test the interface

  • Look at the console output

At this point, the basic architecture is in place. This article is mainly used to record some knowledge points and problems encountered in the learning process, if there are any deficiencies welcome to point out in the comment area. Thank you. OVO