NestJS 里的 provider 是一个很大的概念。
最常见的 provider,就是 service。
// 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;
}
}类比成机场内部:
Controller 负责接待乘客
Service 负责真正调度航班这是 NestJS 的经典分层:
请求
↓
Controller
↓
Service / Provider
↓
Repository / ORM / 外部系统
↓
返回结果一旦你把业务逻辑塞回 Controller,这条线就断了。