Node.js Course
Node.js
/
Advanced

Service Layer Pattern

Definition

An architectural pattern that defines an application's boundary with a layer of services that establishes a set of available operations and coordinates the application's response in each operation.

Explain Like I'm New

If the Controller is the Waiter, and the Repository is the Chef, the Service Layer is the Restaurant Manager. The Waiter shouldn't be making complex business decisions (like checking if a user has enough funds, calculating tax, and applying discounts). The Waiter (Controller) should just pass the request to the Manager (Service). The Service does all the heavy business logic, calls the Chef (Repository), and gives the final result back to the Waiter.

Real World Example

A 'Checkout' route. The Controller extracts the UserID and Cart from the HTTP request. It passes them to `CheckoutService.processOrder()`. The Service validates inventory, charges the Stripe API, sends an email via SendGrid, and tells the Repository to save the order. The Controller just replies '200 OK'.

Common Use Cases

  • •Keeping Controllers 'skinny'
  • •Reusing complex logic across different routes or cron jobs

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • Should business logic (like calculating taxes) live in the Controller or the Service Layer?

intermediate

  • Why do we want 'Skinny Controllers' and 'Fat Services'?

Flash Cards

Question

Where does business logic live?

Click to reveal answer
Answer

In the Service Layer.

Question

Skinny Controllers?

Click to reveal answer
Answer

Controllers should only handle HTTP concerns (parsing `req.body`, checking headers, sending `res.status`). If you put business logic in a Controller, you can't reuse it. By putting it in a Service, you can call that exact same logic from an HTTP route, a WebSocket event, or a nightly Cron Job!