从零入门 NestJS:构建你的第一个 REST API(二) 选择 NestJS

307 阅读3分钟

导语:为什么选择 NestJS?

NestJS 是一个专为构建高可维护性、可扩展服务端应用而设计的 Node.js 框架。它采用 TypeScript,结合了面向对象、函数式和响应式编程理念,让后端开发变得像搭积木一样有条理。

核心优势

  • 模块化开发:每个功能都可以拆分为独立模块,方便多人协作和后期维护。
  • 依赖注入机制:通过依赖注入解耦各层逻辑,提升代码复用性和可测试性。
  • 企业级支持:内置中间件、拦截器、管道等丰富功能,适合中大型项目。
  • TypeScript 原生支持:类型安全,开发体验更好。

NestJS 适合需要清晰架构、易于维护和扩展的中大型 Node.js 项目。如果你熟悉 Angular,会发现 NestJS 的开发体验非常相似。


实战场景:团队协作中的模块拆分

假设你和同事一起开发一个电商平台,NestJS 允许你将用户、商品、订单等功能拆分为独立模块。每个人负责一个模块,互不干扰,开发效率和代码质量都能大幅提升。

目录结构示例:

src/
  app.module.ts         // 主模块
  user/
    user.module.ts      // 用户模块
    user.controller.ts  // 用户控制器
    user.service.ts     // 用户服务

完整代码示例:

// app.module.ts
import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';

@Module({
  imports: [UserModule], // 注册用户模块
})
export class AppModule {}

// user/user.module.ts
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@Module({
  controllers: [UserController],
  providers: [UserService],
})
export class UserModule {}

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

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

  @Get('profile')
  getProfile() {
    return this.userService.getProfile();
  }

  @Post('register')
  register(@Body() body: { username: string; email: string }) {
    return this.userService.register(body);
  }
}

// user/user.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class UserService {
  getProfile() {
    return { username: 'nest_user', email: 'user@example.com' };
  }

  register(data: { username: string; email: string }) {
    // 实际项目中这里会有数据库操作
    return { message: '注册成功', user: data };
  }
}

通过模块拆分和依赖注入,每个业务模块都能独立开发、测试和维护,避免了"多人一锅粥"的混乱局面。


NestJS 与 Express、Koa 的区别

NestJS、Express 和 Koa 都是 Node.js 服务端开发常用框架,但它们的定位和设计理念有明显差异:

  • Express:极简、灵活,适合小型项目或需要高度自定义的场景。
  • Koa:由 Express 团队打造,更加轻量,支持 async/await,适合中间件驱动的开发。
  • NestJS:高度模块化,内置依赖注入,适合中大型项目和团队协作,开发体验类似于 Angular。

对比表:

特性NestJSExpressKoa
架构风格模块化、OOP、DI极简、函数式极简、函数式
依赖注入内置
TypeScript 支持原生需手动配置需手动配置
中间件机制支持支持支持
路由系统装饰器+模块路由函数路由函数
适用场景中大型、企业级小型/中型小型/中型
学习曲线略高
官方文档完善完善一般

总结:NestJS 更适合需要清晰架构、多人协作和长期维护的项目,而 Express/Koa 更适合快速开发和简单场景。