DEV Community

Discussion on: How I structure my REST APIs

Collapse
 
utkal97 profile image
Utkal

Thank you for the nice post. I am beginner to Expressjs and have some beginner doubts :-
1) Why should we have "services" seperately (why not write the logic in controllers themselves?)
2) If controllers are to be kept seperate from services for some reason, how are routes and controllers different (since the controllers and routes are accepting the same parameters and the controller expects results from service, why can't a route directly call service instead and respond to the request?)?

I hope that I am missing some case where each of them is to be seperate, but can't get it.

Collapse
 
larswaechter profile image
Lars Wächter • Edited

1)
If we have the services (logic) separated from the controllers, we can query the required data from anywhere else in our codebase. Otherwise you have to write the same code every time again just to get the same data. (or you send a request to the API itself -> bad)

2)
A route does not directly call a service, because before calling the service the controller takes care of the incoming HTTP request, validation and the outgoing response. In a controller we might send different HTTP status codes or prepare the data before sending it back to the client. In a service we just load the data and handle the business logic. It does not care about where it gets called from.

Let's say you call a service, that expects parameters, directly from a route. Now the router sends the incoming HTTP request as argument to your service. But what if you want to call the service from within your codebase and not from an incoming HTTP request? You can't really pass a HTTP request as argument.

Collapse
 
utkal97 profile image
Utkal

Thank you. Everything is clarified now.