프로바이더 등록하기
Coddy Node.js 여정의 TypeScript와 NestJS 섹션에 포함된 레슨. 24개 중 10번째.
Nest는 모듈의 providers에 나열된 클래스만 생성합니다. 제공자는 다른 제공자를 요청할 수 있으며, 이들 모두 등록되어 있어야 합니다.
@Injectable()
export class OrdersService {
constructor(private readonly mailer: MailerService) {}
}MailerService가 모듈의 providers에 없으면 앱이 시작되지 않고, Nest는 찾지 못한 항목을 정확히 알려 줍니다.
Nest can't resolve dependencies of the OrdersService (?).
Please make sure that the argument MailerService at index [0]
is available in the OrdersModule module.?는 누락된 생성자 인수를 나타내며, 메시지에는 수정해야 할 클래스와 모듈의 이름이 표시됩니다.
챌린지
쉬움- 시작 코드에
ClockService가 추가되어 있습니다.TasksService에서 이를 요청하고 새 작업마다createdAt: this.clock.now()를 지정하세요. TasksModule에ClockService를 등록하세요.- 제목을 지정해
POST /tasks를 전송하세요. 그런 다음providers에서ClockService를 제거하고 ‘실행’을 누른 뒤 오류를 확인하고 다시 추가하세요.
직접 해보기
import { Injectable, NotFoundException } from '@nestjs/common';
export interface Task {
id: number;
title: string;
done: boolean;
createdAt?: string;
}
@Injectable()
export class TasksService {
private tasks: Task[] = [
{ id: 1, title: 'Write the README', done: true, createdAt: '2026-01-05T09:00:00.000Z' },
{ id: 2, title: 'Fix the login bug', done: false, createdAt: '2026-01-06T14:30:00.000Z' },
{ id: 3, title: 'Plan the sprint', done: false, createdAt: '2026-01-07T08:15:00.000Z' },
];
findAll(done?: string): Task[] {
if (done === undefined) {
return this.tasks;
}
return this.tasks.filter((task) => task.done === (done === 'true'));
}
findOne(id: number): Task {
const task = this.tasks.find((task) => task.id === id);
if (!task) {
throw new NotFoundException(`Task ${id} not found`);
}
return task;
}
create(title: string): Task {
const id = Math.max(0, ...this.tasks.map((task) => task.id)) + 1;
const task = { id, title, done: false };
this.tasks.push(task);
return task;
}
remove(id: number): void {
this.findOne(id);
this.tasks = this.tasks.filter((task) => task.id !== id);
}
}
TypeScript와 NestJS의 모든 레슨
직접 연습해 보세요: Express 플레이그라운드