0
0
NestjsConceptBeginner · 3 min read

What is Service in NestJS: Explanation and Example

In NestJS, a service is a class that contains business logic and handles data processing. It acts like a helper that your controllers call to perform tasks, keeping your code organized and reusable.
⚙️

How It Works

Think of a NestJS service as a kitchen helper in a restaurant. The controller is like the waiter who takes orders from customers (users). Instead of cooking the food themselves, the waiter asks the kitchen helper (service) to prepare the dishes. This separation keeps things clean and efficient.

In NestJS, services are classes marked with the @Injectable() decorator. This tells NestJS that the service can be injected into other parts of the app, like controllers. When a controller needs to perform a task, it calls the service's methods. This way, the controller focuses on handling requests and responses, while the service handles the core logic.

💻

Example

This example shows a simple service that returns a greeting message. The controller calls the service to get the message and sends it back to the user.

typescript
import { Injectable } from '@nestjs/common';

@Injectable()
export class GreetingService {
  getGreeting(): string {
    return 'Hello from the service!';
  }
}

import { Controller, Get } from '@nestjs/common';
import { GreetingService } from './greeting.service';

@Controller('greet')
export class GreetingController {
  constructor(private readonly greetingService: GreetingService) {}

  @Get()
  getHello(): string {
    return this.greetingService.getGreeting();
  }
}
Output
When you visit /greet, the response is: "Hello from the service!"
🎯

When to Use

Use services in NestJS whenever you need to separate your business logic from the code that handles HTTP requests. This helps keep your app organized and easier to maintain.

For example, if your app needs to fetch data from a database, calculate values, or call external APIs, put that logic inside a service. Then, your controllers just call the service methods to get the job done.

This approach is great for real-world apps where you want to reuse logic in multiple places or write tests easily.

Key Points

  • Services hold business logic and data processing.
  • Controllers call services to keep code clean and focused.
  • Services are marked with @Injectable() for dependency injection.
  • Using services improves code reuse and testability.

Key Takeaways

A service in NestJS is a class that contains business logic and can be injected into controllers.
Services help keep controllers simple by handling data processing and tasks.
Mark services with @Injectable() to enable dependency injection.
Use services to organize code, improve reuse, and make testing easier.