Reputation: 55
I am building a web service with node.js and express.js and trying to use a MVC architecture for the first time.
I have an html form that the user sends to a specific route (suppose POST to /formprocessing). In the backend I have to do several tasks when I receive the form data.
So, at the beginning I splitted the code in different controllers so each controller does one task. For example, formController saves the data in de db, processingController does some calculations and zipController sends the zip file to the client. However, now I am trying to put together all three parts when handling the request but what I found on the internet is that I should not call one component from another one (calling a controller from another one). Then which is the correct approach I should use? Wrapping the controllers as util functions and calling them from just one controller?
Upvotes: 1
Views: 1612
Reputation: 2465
The idea of Controller
is that this is an entity that handles the Transport layer of your application. Ideally, the only thing that calls Controller should be your transport layer, e.g. HTTP request because it usually contains some Transport layer-specific code.
Typically application has three levels, Controller
, Services
, Models
.
Controller
handles Transport layers and calls some Services
.Service
contains business logic and interacts with Models
to persist changes in the database.Models
interact with a database.Thus when you need to do something that is executed in a controller, you will be using Service
that has nothing to do with a transport layer. So you could have service A
and it needs to do something that does service B
you can use methods of service B
inside service A
to achieve what it needs, without calling controller.
P.S. Here is some useful reading for you https://dev.to/santypk4/bulletproof-node-js-project-architecture-4epf
Upvotes: 0