Menu
CoddyTech

Mendaftarkan Penyedia

Termasuk bagian TypeScript dan NestJS dalam perjalanan Node.js di Coddy. Pelajaran 7 dari 17.

Nest hanya membuat class yang dicantumkan modul di providers. Sebuah provider dapat meminta provider lain, dan semuanya harus didaftarkan.

@Injectable()
export class OrdersService {
    constructor(private readonly mailer: MailerService) {}
}

Jika MailerService tidak ada di providers milik modul, aplikasi tidak akan dimulai, dan Nest menjelaskan dengan tepat apa yang tidak dapat ditemukan:

Nest can't resolve dependencies of the OrdersService (?).
Please make sure that the argument MailerService at index [0]
is available in the OrdersModule module.

? menandai argumen constructor yang hilang, dan pesan tersebut menyebutkan class serta modul yang perlu diperbaiki.

challenge icon

Tantangan

Mudah
  • Starter menambahkan ClockService. Minta layanan ini di TasksService dan berikan createdAt: this.clock.now() kepada setiap tugas baru.
  • Daftarkan ClockService di TasksModule.
  • Kirim POST /tasks dengan judul. Lalu keluarkan ClockService dari providers, tekan Jalankan, baca error, lalu masukkan kembali.

Coba sendiri

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);
    }
}

Semua pelajaran di TypeScript dan NestJS

Latihan sendiri: Playground Express