A Service
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 6 of 17.
The controller holds the tasks itself, so no other part of the app can reach them. Data and logic belong in a provider: a class Nest creates and hands to whoever asks for it.
@Injectable()
export class BooksService {
private books = [{ title: 'Dune' }];
}
@Controller('books')
export class BooksController {
constructor(private readonly booksService: BooksService) {}
}@Injectable() marks the class, and the module lists it in providers. A class asks for it by naming it in its constructor: this is dependency injection. Nest reads the parameter's type, which the compiler keeps for decorated classes, creates one instance for the whole app and passes that same instance to every class that asks. The data is shared, and a test can pass in a fake instead.
This lesson opens with the controller already calling this.tasksService.
Challenge
Easy- Make
TasksServiceinjectable, give itcreate(title)andremove(id), the work your controller did in lesson 5, and list it inTasksModule'sproviders. - Ask for it in
TasksController's constructor. - Send
POST /taskswith{ "title": "Buy milk" }, thenGET /tasks, thenDELETE /tasks/99.
Try it yourself
import { NotFoundException } from '@nestjs/common';
export interface Task {
id: number;
title: string;
done: boolean;
createdAt?: string;
}
// Make this class a provider that Nest can inject.
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;
}
// Move the create and remove logic from the controller here.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.