Application structure - brightstudent/backend GitHub Wiki

Application structure

My structure consists of assets and views. Assets contains all my css and javascript files including my images. Inside the view directory you can find two directories: views and partials. Pages contains all the html pages the user gets to see. Partials contains parts that are written in html and can be reused throughout the website using the templating engine (EJS).

Old structure

New structure

To make things even more structured I refined the application structure using the MVC model. I also cleaned up the assets file by creating a separate directory for my JavaScript files.

New structure

MVC Model

MVC Model

Model-view-controller (MVC) is a design pattern that divides complex application architecture into three pieces with distinct responsibilities: data model (model), data presentation (view), and application logic (controller). Separating these elements improves code readability and reusability. It also implies that modifications to the user interface, for example, have no direct impact on the data model and vice versa.

  • Model: Defines the representation of the information with which the application works. Raw data is given meaning by adding relationships between data and logic.
  • View: Information is displayed through the View. User interface elements will be defined in this section. The view does not do any processing on the displayed data (such as computations, checks, etc.).
  • Controller: The controller processes and responds to events, which are usually the result of user actions.

MVC implementation

First of all I created two separate controllers: one for the homepage and the other for the liking functionality. If we take the latter as an example (see the screenshot below) you can see that all requests surrounding this functionality is defined in this controller.

  1. This controller makes a request using the get method to get all the favored restaurants;
  2. This controller makes a request using the post method to add an item to the favorites list, by applying a boolean of true;
  3. This controller also makes a request using the delete method to remove an item from the favorites list by changing the boolean back to false.

Controllers

To get this functionally from here to my server I use routes. Instead of requiring each route separately, I created an index.js file in my routes directory. This file exports both controllers using a function that contains two parameters module.exports = (app, db) => {...}. The first parameter tells the server which router to use and the second parameter connects to my database.

By doing this I minimized code duplication and I only need one rule of code to require and use my controllers require('./routes')(app, db).

Routes server.js