Thin controllers, smart services
Controllers should only translate HTTP into calls. Business logic — finding dishes, calculating totals — lives in providers (usually *services*). And you never new them yourself: Nest creates one and injects it wherever it's asked for. That's dependency injection.
@Injectable and constructor injection
import { Controller, Get, Param, ParseIntPipe } from "@nestjs/common";
import { DishesService } from "./dishes.service";
@Controller("dishes")
export class DishesController {
constructor(private readonly dishesService: DishesService) {}
@Get()
findAll() {
return this.dishesService.findAll();
}
@Get(":id")
findOne(@Param("id", ParseIntPipe) id: number) {
return this.dishesService.findOne(id);
}
}- A provider must be listed in a module's providers to be injectable there.
- By default providers are singletons: one instance shared by everyone in the app.
- DI makes testing easy: swap the real service for a fake one (later lesson).