Services in NestJS

Learn how to use the service in NestJS and understand a singleton behavior of a provider.

Providers are a critical concept in NestJS, responsible for defining and injecting dependencies throughout an application. Services are a specific type of provider that handles the business logic of an application. Using services promotes modularity and reusability, making the codebase easy to maintain, test, and scale. Additionally, services can be injected as dependencies wherever needed, making sharing functionality between different parts of the codebase easy.

Creating a service

Now, in our school management system, we need a way to control the list of students. To achieve this, let’s create a StudentsService to encapsulate the business logic of managing students.

Here’s how we can create a StudentsService:

Press + to interact
students.service.ts
interface.ts
import { Injectable } from '@nestjs/common';
import { Student } from "./interface.ts"
@Injectable()
export class StudentsService {
private readonly students: Student[] = [];
create(student: Student) {
this.students.push(student);
}
findAll(): Student[] {
return this.students;
}
}

In the students.service.ts file, we define a StudentsService class that handles the business logic related to students. The students property is a private array that will hold the list of students. The create method accepts a Student object as input and adds it to the ...