Up until this point, the controllers we wrote for our application have been extremely basic. They were started with a simple task of sending text responses to the client. In the previous chapter, we updated the controllers so that they render an HTML view and send the HTML code to the client, instead of a simple text response. The primary job of a controller is to act as the entity, which holds the logic that makes all of the necessary decisions to properly render a response to the client. In our case, this means retrieving and/or generating the data necessary for a page to appear complete.
In this chapter, we will:
A controller can be defined as the entity that will be responsible for manipulating models and initiating the view render process with the data received from the corresponding models. In the code we have developed so far, we can see that the express router instance is used to tie functions to a corresponding route. These functions are nothing but controllers. For every route that we create in our router, two parameters are necessary:
/images/:image_id
For any route that has to do with images, we rely on the images
controller. Likewise, any route that has to do with the home page relies on the home
controller, and so on and so forth.
The steps we will take to define our controllers in our app are purely organizational and based on personal preference. We created our controllers as modules so that our router wasn't a big, long convoluted mess of spaghetti code. We could have just as easily kept all of the logic contained in our controllers as functions directly within the routes themselves, but this would have been an organizational mess and made for very hard-to-read code to maintain later.
As our sample app is fairly small, we only have two controllers currently: home
and image
. It is the responsibility of these controllers to build the appropriate view models for our HTML pages and render the actual pages as well. Any logic that is required to execute per page and build the view model will be done so via our controllers.
18.225.55.151