Registro de proveedores
Parte de la sección TypeScript y NestJS del Journey de Node.js de Coddy. Lección 10 de 24.
Nest solo crea las clases que un módulo enumera en providers. Un proveedor puede solicitar otro proveedor, y todos deben estar registrados.
@Injectable()
export class OrdersService {
constructor(private readonly mailer: MailerService) {}
}Si falta MailerService en providers del módulo, la aplicación no se inicia y Nest indica exactamente qué no pudo encontrar:
Nest can't resolve dependencies of the OrdersService (?).
Please make sure that the argument MailerService at index [0]
is available in the OrdersModule module.? señala el argumento faltante del constructor, y el mensaje indica la clase y el módulo que hay que corregir.
Desafío
Fácil- El código inicial añade
ClockService. Solicítalo enTasksServicey asigna a cada tarea nuevacreatedAt: this.clock.now(). - Registra
ClockServiceenTasksModule. - Envía
POST /taskscon un título. Después, quitaClockServicedeproviders, pulsa «Ejecutar», lee el error y vuelve a añadirlo.
Pruébalo tú mismo
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);
}
}
Todas las lecciones de TypeScript y NestJS
1Fundamentos de Nest
Clases y métodosHola, NestRegistro de un controlador4Guards, filtros e interceptores
Guards2Proveedores
Entradas del constructorUn servicioRegistro de proveedoresPractica por tu cuenta: Playground de Express