Nestjs: Creating a project with CLI

Neo Luo
4 min readJun 16, 2024

--

Preface

This chapter briefly introduces how to nestjs CLIquickly create a NestJS project and API interface module, and then request the interface through Postman. The demo introduces the core Moduleconcepts of NestJS, so that students can better get started with NestJS applications.

Demo effect (postman requests a customized interface)

environment

You need to support the node environment locally. Please click here to download the node environment.

1. Create a nestjs project

First install globally @nestjs/cliand create a projecthello-nestjs

npm i -g @nestjs/cli
nest new hello-nestjs

During the creation process, the default installation method can be selected and npmyou can just press Enter. After the installation is successful, switch to the project directory and run npmthe command to start the project:

cd hello-nestjs
npm run start:dev

After the startup is successful, the initial interface is used postmanto request localhost:3000 using get, which will returnHello World!

2. Interpretation of catalog codes

Project directory created by nestjs Cli:

hello-nestjs/
├── src/
│ ├── app.controller.ts
│ ├── app.controller.spec.ts
│ ├── app.module.ts
│ ├── app.service.ts
│ └── main.ts // entry main
├── test/
├── node_modules/
├── .eslintrc.js
├── .prettierrc
├── nest-cli.json
├── package.json
├── tsconfig.build.json
└── tsconfig.json

Here we introduce the main files, including the entry file 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);
}
bootstrap();

This is the entry point for the application. It uses NestFactoryto create a Nest application instance and listen on the specified port (here 3000)

Project root moduleapp.module.ts

// app.module.ts

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

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

All modules added by subsequent development need importsto be referenced by the root module , similar to the figure:

Basic controller AppController, the controller handles the incoming HTTP request and returns the response. Here a GETrequest handler is definedgetHello

// AppController
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();
}
}

Basic service AppService, which contains business logic, generally serves the control layer. getHelloThe method here returns a simple string.

// app.service.ts

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

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

3. Customize a Module

Through the above introduction to the main file functions, students should have a certain understanding of the file functions. Next, create a named catmodule. Here, nest clithe module is quickly created through scaffolding.

 nest g mo cat # create module 
nest g co cat --no-spec # create controller
nest g s cat --no-spec # create service

Where catis the module name, --no-specdoes not create a unit test file, interested students can click to learn more ( cli documentation )

At this time, srca new catdirectory will be added under the directory, which includes the following files:

1. cat.moduleModule entry

2. cat.controllerAPI interface control layer

3. cat.serviceBasic Services Department

nest cliThe newly generated CatModulemodule will be automatically importsregistered to the root module

// app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
+ import { CatModule } from './cat/cat.module';

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

CatControllerNext, create an getinterface in the control layer

// cat.controller

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

@Controller('cat')
export class CatController {
@Get()
create(): string {
return 'This action adds a new cat'
}
}

By postmanaccessing localhost:3000/catthe request method: GET, the string will be returned: This action adds a new cat

In daily development, controllerthe business logic processing and specific return after the request will servicebe processed in the layer, so the basic layer cat.controlleris introduced in the specific return value.cat.servicecat.service

// cat.controller

import { Controller, Get } from '@nestjs/common';
+ import { CatService } from './cat.service';

@Controller('cat')
export class CatController {
// 构造时注入 CatService
+ constructor(private readonly catService: CatService) { }

@Get()
create(): string {
- return 'This action adds a new cat'
+ return this.catService.createCat()
}
}
// cat.service.ts

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

@Injectable()
export class CatService {
createCat(): string {
return 'This action adds a new cat(form CatService)'
}
}

Visiting again localhost:3000/catwill return the string: This action adds a new cat (form CatService)

Summarize

This chapter mainly introduces how to create a simple nestproject and customize the module interface. The nest application is App.modulebased on the root module. Subsequent new modules need to be added App.modulein imports. Each module has: module(module layer), controller(control layer) service(basic service)

--

--

Neo Luo

I am a full stack developer, engaged in development for more than 10 years, developing e-commerce, tourism, finance, web3, ai, I will share more