Appearance
NestJS快速入门
NestJS是一个用于构建高效、可扩展的Node.js服务器端应用程序的框架。它利用JavaScript的面向对象编程(OOP)、函数式编程(FP)和函数响应式编程(FRP)的元素,深受Angular的启发。
安装NestJS
系统要求
- Node.js 12.x 或更高版本
- npm 6.x 或更高版本
安装CLI工具
bash
npm install -g @nestjs/cli
创建新项目
bash
nest new my-nestjs-app
cd my-nestjs-app
项目结构
创建的项目具有以下结构:
my-nestjs-app/
├── src/
│ ├── app.module.ts
│ ├── app.controller.ts
│ ├── app.service.ts
│ └── main.ts
├── test/
├── node_modules/
├── nest-cli.json
├── package.json
├── tsconfig.json
├── tsconfig.build.json
└── README.md
基础概念
模块 (Module)
模块是带有@Module()装饰器的类。@Module()装饰器提供元数据,Nest用来组织应用程序结构。
typescript
// 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 {}
控制器 (Controller)
控制器负责处理传入的请求并将响应返回给客户端。
typescript
// app.controller.ts
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();
}
}
服务 (Provider)
服务或提供者是普通类,用@Injectable()装饰器注释。
typescript
// app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
主入口点
typescript
// 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();
生成器命令
Nest CLI提供了代码生成器,可以快速创建各种组件:
bash
# 生成控制器
nest generate controller users
# 生成服务
nest generate service users
# 生成模块
nest generate module users
# 生成拦截器
nest generate interceptor logging
# 生成守卫
nest generate guard auth
# 生成管道
nest generate pipe validation
# 生成网关
nest generate gateway events
# 生成微服务提供者
nest generate microservice micro
# 简写命令
nest g co users # controller
nest g s users # service
nest g mo users # module
nest g gu auth # guard
nest g pi validation # pipe
路由处理
基础路由
typescript
import { Controller, Get, Post, Put, Delete, Param, Body } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
@Get(':id')
findOne(@Param('id') id: string): string {
return `This action returns a #${id} cat`;
}
@Post()
create(@Body() createCatDto: any): string {
return 'This action adds a new cat';
}
@Put(':id')
update(@Param('id') id: string, @Body() updateCatDto: any): string {
return `This action updates a #${id} cat`;
}
@Delete(':id')
remove(@Param('id') id: string): string {
return `This action removes a #${id} cat`;
}
}
路由参数和查询参数
typescript
import { Controller, Get, Query, Param } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get(':id')
findOne(
@Param('id') id: string,
@Query('includeProfile') includeProfile: boolean
): string {
return `User ID: ${id}, Include Profile: ${includeProfile}`;
}
@Get()
findAll(
@Query('page') page = 1,
@Query('limit') limit = 10
): string {
return `Page: ${page}, Limit: ${limit}`;
}
}
依赖注入
NestJS使用构造函数注入来解决依赖关系:
typescript
import { Injectable } from '@nestjs/common';
import { CatsService } from './cats.service';
@Injectable()
export class CatsController {
constructor(private catsService: CatsService) {}
async findOne(id: string) {
return this.catsService.findOne(id);
}
}
中间件
typescript
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log('Request...', req.method, req.path);
next();
}
}
在模块中应用中间件:
typescript
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.forRoutes('cats');
}
}
数据传输对象 (DTO)
typescript
// create-cat.dto.ts
export class CreateCatDto {
readonly name: string;
readonly age: number;
readonly breed: string;
}
在控制器中使用:
typescript
@Post()
async create(@Body() createCatDto: CreateCatDto) {
return 'This action adds a new cat';
}
运行应用
bash
# 开发模式
npm run start
# 开发模式(监听文件更改)
npm run start:dev
# 生产模式
npm run start:prod
配置
NestJS应用程序可以通过环境变量进行配置:
typescript
// app.module.ts
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true, // 使配置模块全局可用
}),
],
})
export class AppModule {}
使用配置服务:
typescript
// app.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class AppService {
constructor(private configService: ConfigService) {}
getDatabaseHost(): string {
return this.configService.get<string>('DATABASE_HOST');
}
}
这就是NestJS的快速入门指南。通过这些基础概念,您可以开始构建您的第一个NestJS应用程序。