Node 后端写久了会发现一个问题:Express 给你的是”自由”,路由、校验、鉴权、错误处理全靠自己拼,十个项目十种结构。NestJS 的价值就是把这套结构定下来——它借鉴了 Angular 的依赖注入和模块化,让 Node 项目也有清晰的分层。这篇是入门部分的梳理。
初始化
1 2
| npm i -g @nestjs/cli nest new my-app
|
生成的项目结构:
1 2 3 4 5 6
| src ├── app.controller.ts ├── app.controller.spec.ts ├── app.module.ts ├── app.service.ts └── main.ts
|
main.ts 是入口:
1 2 3 4 5 6 7 8 9 10 11 12
| import { NestFactory } from '@nestjs/core' import { AppModule } from './app.module' import { ValidationPipe } from '@nestjs/common'
async function bootstrap() { const app = await NestFactory.create(AppModule) app.setGlobalPrefix('api') app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true })) app.enableCors() await app.listen(3000) } bootstrap()
|
模块:应用的边界
1 2 3 4 5 6 7 8 9 10 11 12
| import { Module } from '@nestjs/common' import { UsersController } from './users.controller' import { UsersService } from './users.service'
@Module({ imports: [], controllers: [UsersController], providers: [UsersService], exports: [UsersService] }) export class UsersModule {}
|
@Module 的四个字段职责很清晰:
| 字段 |
含义 |
imports |
依赖的其他模块 |
controllers |
对外暴露的路由 |
providers |
本模块内的服务、守卫、拦截器等 |
exports |
允许其他模块使用的 provider |
关键一点:providers 默认是模块私有的。别的模块想用 UsersService,必须在 exports 里声明,并且对方 imports: [UsersModule]。这是 Nest 和 Angular 最大的不同(Angular 的 provider 是全局树),也是最容易踩的坑——“明明注入了却报 Nest can't resolve dependencies“。
控制器:只做参数解析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import { Controller, Get, Post, Body, Param, Query, ParseIntPipe } from '@nestjs/common' import { UsersService } from './users.service' import { CreateUserDto } from './dto/create-user.dto'
@Controller('users') export class UsersController { constructor(private readonly usersService: UsersService) {}
@Get() findAll(@Query('page', ParseIntPipe) page = 1) { return this.usersService.findAll(page) }
@Get(':id') findOne(@Param('id', ParseIntPipe) id: number) { return this.usersService.findOne(id) }
@Post() create(@Body() dto: CreateUserDto) { return this.usersService.create(dto) } }
|
控制器里不要写业务逻辑,也不要做数据库操作。它的职责只有三个:拿参数、调服务、返回结果。参数校验交给 Pipe,权限交给 Guard,这是后面几层要处理的事。
服务:业务逻辑层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import { Injectable, NotFoundException } from '@nestjs/common'
@Injectable() export class UsersService { private readonly users = new Map<number, any>()
findAll(page: number) { const list = [...this.users.values()] const size = 10 return { list: list.slice((page - 1) * size, page * size), total: list.length } }
findOne(id: number) { const user = this.users.get(id) if (!user) { throw new NotFoundException(`用户 ${id} 不存在`) } return user }
create(dto: { name: string; email: string }) { const id = Date.now() const user = { id, ...dto } this.users.set(id, user) return user } }
|
@Injectable() 是让类进入 DI 容器的标记。抛 NotFoundException 而不是 throw new Error(),是因为 Nest 内置了异常过滤器,前者会自动映射成 404 + 统一响应体。
DTO 与参数校验
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| import { IsEmail, IsNotEmpty, IsOptional, MinLength } from 'class-validator'
export class CreateUserDto { @IsNotEmpty({ message: '用户名不能为空' }) @MinLength(2) name: string
@IsEmail({}, { message: '邮箱格式不正确' }) email: string
@IsOptional() avatar?: string }
|
配合全局 ValidationPipe,非法请求会在进入控制器之前被拦下,返回 400 和具体字段错误。这里两个选项值得开:
whitelist: true:剔除 DTO 里没声明的字段,防止客户端偷偷传 role: 'admin' 这种提权字段
transform: true:把 query 的字符串自动转成 DTO 里声明的类型
配置与环境变量
1 2 3 4 5 6 7 8 9 10 11 12
| import { ConfigModule } from '@nestjs/config'
@Module({ imports: [ ConfigModule.forRoot({ isGlobal: true, envFilePath: [`.env.${process.env.NODE_ENV}`, '.env'] }) ] }) export class AppModule {}
|
1 2 3
| constructor(private config: ConfigService) { const port = this.config.get<number>('PORT', 3000) }
|
isGlobal: true 省去每个模块都 import 一遍的麻烦。但要注意,ConfigService.get 不做类型校验,建议包一层自己的 ConfigService,把 get('DB_URL') 收敛成强类型方法。
生命周期与启动
1 2 3 4 5 6 7
| async function bootstrap() { const app = await NestFactory.create(AppModule, { bufferLogs: true }) app.enableShutdownHooks() const port = process.env.PORT ?? 3000 await app.listen(port) console.log(`server listening on ${port}`) }
|
enableShutdownHooks() 一定要开,否则容器滚动更新时进程被直接杀掉,数据库连接池、消息队列不会优雅关闭,可能丢消息。
和 Express 相比的取舍
优势:
- 分层明确,新人上手看目录就知道代码在哪
- DI 让单元测试非常容易(直接 new Service 或 mock provider)
- 守卫、拦截器、管道、异常过滤器四层扩展点,横切逻辑不用散在路由里
代价:
- 概念多,
Module/Provider/Guard/Interceptor 得花时间理解
- 抽象层带来的调试成本,报错栈比 Express 深
- 简单接口用 Nest 确实”重”
判断标准很简单:如果项目只有十几个接口、不会长期维护,Express/Koa 更快;如果是团队协作、要长期迭代的业务系统,Nest 的结构收益远大于学习成本。这也是为什么它在 2022 年之后的中大型 Node 项目里迅速成了默认选项。