全书目录

第七篇:NestJS 完全指南 —— 国际机场总调度宇宙

第六章:Provider / Service —— 真正干活的是调度中心

1 分钟 110 字 第 186 / 962 个阅读单元

NestJS 里的 provider 是一个很大的概念。
最常见的 provider,就是 service

ts
// src/flights/flights.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateFlightDto } from './dto/create-flight.dto';

type Flight = {
  id: string;
  code: string;
  destination: string;
};

@Injectable()
export class FlightsService {
  private readonly flights: Flight[] = [];

  findAll() {
    return this.flights;
  }

  findOne(id: string) {
    const flight = this.flights.find(item => item.id === id);
    if (!flight) {
      throw new NotFoundException('航班不存在');
    }
    return flight;
  }

  create(dto: CreateFlightDto) {
    const flight: Flight = {
      id: crypto.randomUUID(),
      code: dto.code,
      destination: dto.destination,
    };
    this.flights.push(flight);
    return flight;
  }
}

类比成机场内部:

text
Controller 负责接待乘客
Service 负责真正调度航班

这是 NestJS 的经典分层:

text
请求
  ↓
Controller
  ↓
Service / Provider
  ↓
Repository / ORM / 外部系统
  ↓
返回结果

一旦你把业务逻辑塞回 Controller,这条线就断了。