This article is a quick guide to getting started with NestJS. It does not contain a detailed list of apis and capabilities. If necessary, please refer to the official documentation: docs.nestjs.com.
Introduction to the
NestJS is a Back-end framework based on Node.js
Why use NestJS
It provides a complete, out-of-the-box back-end architecture. Supports TypeScript, Object Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP). Dependency injection support enables the creation of highly testable, easily extensible, loosely coupled, and easily maintainable back-end applications.
The core concept
-
Controller
The parts that handle requests directly and return responses are built using classes and decorators. Class lets us use object programming, and the decorator lets Nest build routing maps.
// cat.controller.ts
import { Controller, Get } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats'; }}Copy the code
-
Services
The parts responsible for data storage and retrieval are also built using classes and decorators. The @Injectable() here gives the CatService the ability to be managed by the Nest IoC container.
// cat.service.ts
import { Injectable } from '@nestjs/common';
import { Cat } from './interfaces/cat.interface';
@Injectable(a)export class CatsService {
private readonly cats: Cat[] = [];
create(cat: Cat) {
this.cats.push(cat);
}
findAll(): Cat[] {
return this.cats; }}Copy the code
-
Provider
A provider is something that can be injected as a dependency, and almost anything in Nest can be treated as a provider, such as the CatsService in the code above, which is a provider.
The Provider is consumed in the Controller.
// cat.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(a)async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}
@Get(a)async findAll(): Promise<Cat[]> {
return this.catsService.findAll(); }}Copy the code
The Provider also needs to be registered in the Module before it can be injected by Nest.
// cat.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 {}
Copy the code
-
Modules
Classes using the @Module annotation are used by Nest to organize the application structure and resolve modules, provider relationships, and dependencies.
According to the SOLID principle, when we put the related parts together, the file structure of a module would look something like this:
src
|--cats
| |--interfaces
| | |--cat.interface.ts
| |--cats.controller.ts
| |--cats.module.ts
| |--cats.service.ts
|
|--app.module.ts
|--main.ts
Copy the code
App.module. ts is the root module of the application. It must exist and is responsible for organizing other modules within the application.
// app.module.ts
import { Module } from '@nestjs/common';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule {}
Copy the code
-
Middleware Middleware
slightly
-
Exception filters
Nest comes with an exception catcher that handles unhandled exceptions in your code.
Such as unhandled global exception returns, parameter verification failure returns, through the built-in filter to return a fixed format. We can also use filters to customize the format for handling global exception returns while logging the error.
-
Pipeline Pipe
Mainly do some data format conversion and verification work.
Conversion and validation could have been done in a routing processor method, but Nest designed PIPE to handle this work for the sole responsibility principle.
// Format conversion
@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
return this.catsService.findOne(id);
}
Copy the code
Parameter calibration
Nest uses the built-in ValidationPipe and a third-party package called Class-Validator to validate parameters
// Enable global verification
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();
// Define parameter types in controller
@Post(a)create(@Body() createUserDto: CreateUserDto) {
return 'This action adds a new user';
}
Copy the code
-
The guard Guards
Determines whether a request can be processed by the routing processor based on certain conditions, which is mainly used for permission verification.
-
The interceptor Interceptors
There are a few things you can do before or after the routing function executes. For example, fixed formats for global success returns, access logs, etc.
The above is some of the core concepts of NestJS, after reading NestJS should have an overall understanding, combined with the corresponding part of the document, you can master the use of NestJS.