Controllers

A controller can be defined as an 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, the following two parameters are necessary:

  • The first parameter is the string for the route itself, which is /images/:image_id
  • The second parameter is a controller function that will be executed when that route is accessed

For any route that has anything to do with images, we rely on the image controller. Likewise, any route that has anything to do with the home page relies on the home controller, and so on.

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 isn'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 way for a very hard-to-read code to be maintained later on.

As our sample app is fairly small, we currently have only two controllers: home and image. It is the responsibility of these controllers to build the appropriate View models for our HTML pages and to render the actual pages also. Any logic that is required to execute per page and build the View model will be done so via our controllers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.168.203