As you can see the controller is the one passing the necessary information so that
the data from the different models is related.

Request handler should not call other request handlers

This is a rule very similar to the rule for the models. Its main benefit is that
all request are very easy to follow.

You know that they always come from an http request. Then they are then handled by
the controller, which in turn uses one or more models to retrieve or store the
necessary data. Whenever a change is required, you can make it much more easily.

However, sometimes you do some processing and than you want to show another page.
It may be tempting to just call the controller method, instead it is better to use
redirect, just like in the example from above

In the first case we use something specifically from SQL, but the controller should not know
anything about it as it doesn’t care about SQL, instead it cares about how to
best return the appropriate results to the user.

Not only that but it also makes testing more difficult as it provides way too
many cases.

Instead having business specific methods makes your code more readable and specific
for your use case. Not only that but due to its specifics it is also much easier to test.

Models never return http errors or other direct responses

Very often you immediately return the data from your models. Especially when you
create a REST API.

In an API when there is an error you return an HTTP error. As a result, it is
very tempting the error to be generated by the model.

However, HTTP errors have several problems. First, they are not specific enough
and most models are used by multiple controllers. So later when you need to use
your model at another place it will be much more difficult to decide what happens.

Second, HTTP errors are for the controller as it is its responsibility to format
the response.

Models don’t do templates they only care about data

Similar to HTTP errors, templates should not be handled in the model. The model
only provides data, it is not his responsibility to present it in the appropriate
format.

Next

It might not seem obvious but those rules really make developing Node applications
a lot easier.

Your next step might be to try to apply them to your existing code base.

Did you like this article?

Please share it

Enter your email and get our NPM Cheat Sheet for NodeJS Developers and
the links to our 5 most popular articles which have helped thousands of
developers build faster, more reliable and easier to maintain Node applications.