Menu
CoddyTech

تسجيل المزوّدات

جزء من قسم TypeScript وNestJS في رحلة Node.js على Coddy. الدرس 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.

تشير ? إلى وسيطة المُنشئ المفقودة، وتذكر الرسالة اسم الصنف والموديول اللذين يجب إصلاحهما.

challenge icon

التحدي

سهل
  • يضيف المشروع الابتدائي ClockService. اطلبه في TasksService وأضف createdAt: this.clock.now() إلى كل مهمة جديدة.
  • سجّل ClockService في TasksModule.
  • أرسل POST /tasks مع عنوان. ثم أزل ClockService من providers، واضغط على «تشغيل»، واقرأ رسالة الخطأ، ثم أعده.

جرّب بنفسك

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

تدرّب بنفسك: Playground لـ Express