Llus
Llus

Reputation: 55

Is it a bad idea calling a controller from another controller?

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.

  1. First I save the data in the database
  2. Then I must do some data processing
  3. Finally I send a zip file to the client

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

Answers (1)

Ayzrian
Ayzrian

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.

  1. Controller handles Transport layers and calls some Services.
  2. Service contains business logic and interacts with Models to persist changes in the database.
  3. 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

Related Questions