Node.js: Architecting an Express application in the MVC paradigm

Express doesn’t enforce an opinion on how you should structure the Model, View, and Controller (MVC) modules of your application, or whether you should follow any kind of MVC paradigm at all. The MVC pattern is widely used and involves three main architectural pieces. The controller accepts inputs or requests from the user, converting that into commands sent to the model. The model contains the data, logic, and rules by which the application operates. The view is used to present results to the user.

As we learned in the previous chapter, the blank application created by the Express generator provides two aspects of the MVC model:

  • The views directory contains template files, controlling the display portion, corresponding to the view.
  • The routes directory contains code implementing the URLs recognized by the application and coordinates the data manipulation required to generate the response to each URL. This corresponds to the controller.

Since the router functions also call the function to generate the result using a template, we cannot strictly say that the router functions are the controller and that the views templates are the view. However, it’s close enough to the MVC model for it to be a useful analogy.

This leaves us with a question of where to put the model code. Since the same data manipulation can be used by multiple router functions, clearly the router functions should use a standalone module (or modules) containing the model code. This will also ensure a clean separation of concerns—for example, to ease the unit testing of each.

The approach we’ll use is to create a models directory as a sibling of the views and routes directories. The models directory will hold modules to handle data storage and other code that we might call business logic. The API of the modules in the models directory will provide functions to create, read, update, or delete data items—a Create, Read, Update, and Delete/Destroy (CRUD) model—and other functions necessary for the view code to do its thing.

The CRUD model includes the four basic operations of persistent data storage. The Notes application is structured as a CRUD application to demonstrate the implementation each of these operations.

We’ll use functions named create, read, update, and destroy to implement each of the basic operations.

With that architectural decision in mind, let’s proceed with creating the Notes application.

Source: Herron David (2020), Node.js Web Development: Server-side web development made easy with Node 14 using practical examples, Packt Publishing.

Leave a Reply

Your email address will not be published. Required fields are marked *