Skip to content

Services — The Real Workers of NestJS

Welcome to the construction zone! 🚧 If controllers are the traffic cops, then services are the hardworking engineers, builders, and problem solvers behind the scenes.

They handle the actual business logic, data retrieval, calculations, and everything else controllers are too fancy for. 😎

🧠 What is a Service?

A service is a class with a single job: DO STUFF.

Whether it’s talking to the database, validating a form, or calculating how many coffee beans it takes to fuel a dev team — the service does the job. ☕➕👨‍💻

🏗️ Anatomy of a Simple Service

ts
import { Injectable } from "@nestjs/common";

@Injectable()
export class CatsService {
  private cats = ["Whiskers", "Paws", "Claws"];

  findAll() {
    return this.cats;
  }

  create(cat: string) {
    this.cats.push(cat);
    return `Cat ${cat} added 🐱`;
  }
}

🔮 What’s That @Injectable()?

The @Injectable() decorator tells Nest:

“Hey, this class can be used with dependency injection. Feel free to plug me in where needed!” 🔌

This is how the controller gets access to services.

🤝 Using the Service in a Controller

Here’s how you call in the workers:

ts
@Controller("cats")
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  findAll() {
    return this.catsService.findAll();
  }

  @Post()
  create(@Body() cat: string) {
    return this.catsService.create(cat);
  }
}

💡 Pro Tip: The service should be the place where you put all reusable logic. Want to validate something? Query a DB? Send an SMS? Service!

🧰 Services Are Reusable

A service can be injected into:

  • Controllers
  • Other services
  • Guards
  • Interceptors
  • Pipes
  • Your dreams 🛌 (okay maybe not those)

🔄 Lifecycle of a Service

text
1. Nest sees @Injectable()
2. It creates an instance when needed
3. It injects that instance wherever it’s requested

Boom. Dependency injection magic! 🪄

🧱 Real World Analogy

Let’s say your app is a pizza shop:

  • Controller: Takes the customer’s order 🍕
  • Service: Prepares the pizza with sauce, cheese, and disappointment from missing toppings 🧀
  • Database: Stores all your past pizza sins

🧪 Writing Clean Services

Keep it clean, focused, and testable:

❌ Don’t mix controller logic here

✅ Do write all your data-handling and operations here

🏁 Final Thoughts

If your app were a stage, services would be the actors and controllers would be the announcers. 🎭

They don’t take a bow, but without them, your app’s performance would bomb harder than a failed code deploy on Friday at 5PM. 💣

Built by noobs, for noobs, with love 💻❤️