プロバイダーの登録
CoddyのNode.jsジャーニー「TypeScriptとNestJS」セクションの一部。レッスン 10/24。
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プレイグラウンド