一个常见的 RESTFull API 一般包含 controller、service、module 三部分:

  1. --module
  2. --user
  3. --user.contorller.ts
  4. --user.service.ts
  5. --user.module.ts

Controller

控制器负责处理传入的请求和向客户端返回响应。
使用 @Controller() 定义控制器类。
使用 @Get() @Post() 等定义路由
使用 @Request() @Query() @Body() 等获取请求参数

  1. // user.controller.ts
  2. import { Controller, Get, Param} from '@nestjs/common'
  3. @Controller('user')
  4. export class UserController {
  5. @Get('/:id')
  6. async getOne(@Param('id') id: string) {
  7. // TODO 使用 id 获取用户
  8. return { id: 1, name: 'web' }
  9. }
  10. }

详细使用方法,请参考 控制器

Provider

provideer 是 Nest 的一个基本概念,provider 可以用过 constructor 注入依赖关系。
在前面,我们创建了一个简单的控制器 UserController,控制器应处理 HTTP 请求并将更复杂的任务委托给 providers。
我们使用 @Injectable() 声明一个 provider。

  1. // user.service.ts
  2. import { } from '@nestjs/common'
  3. @Injectable()
  4. export class UserService {
  5. async getOne(id: string) {
  6. // mock
  7. return { id, name: 'web' }
  8. }
  9. }

在控制器里使用这个服务类

  1. // user.controller.ts
  2. import { Controller, Get, Param} from '@nestjs/common'
  3. import { UserService } from './user.service.ts'
  4. @Controller('user')
  5. export class UserController {
  6. // constructor 中注入 UserService
  7. constructor(private userService: UserService) {}
  8. @Get('/:id')
  9. async getOne(@Param('id') id: string) {
  10. // 使用 userService
  11. return this.userService.getOne(id)
  12. }
  13. }

详细使用方法,请参考 提供者

Module

模块是具有 @Module 装饰器的类,@Module 装饰器提供了元数据,Nest 用它来组织应用程序结构。
一个应用通常有一个根模块,根模块下有多个子模块。
在上面,我们创建了 UserController 和 UserService,将它们放入同一个功能模块下,即 UserModule。

  1. // user.module.ts
  2. import { Module } from '@nestjs/common'
  3. import { UserController } from './user.controller'
  4. import { UserService } from './user.service'
  5. @Module({
  6. providers: [UserService],
  7. controllers: [UserController]
  8. })
  9. export class UserModule {}

详细使用方法,请参考 模块

现在一个完整的 user 模块已经完成,我们需要做的最后一件事是将这个模块导入根模块。

  1. // app.module.ts
  2. import { Module } from '@nestjs/common'
  3. import { UserModule } from 'path/to/user.module'
  4. @Module({
  5. imports: [UserModule]
  6. })
  7. export class AppModule {}