API Design in Node.js, v3 Controllers & Models Overview
This course has been updated! We now recommend you take the API Design in Node.js, v4 course.
Transcript from the "Controllers & Models Overview" Lesson
>> Scott Moss: The next lesson, which is basically gonna be controllers and working with the models. So we created schemas that created models and we have routes. So we're really only missing one thing as far as having a API that does something, is we need some controllers. So that's what we're gonna be working on next.
[00:00:18] So routes and controllers. Basically controllers, like I said before, are just middleware but with the intent of returning some data. That is the only difference in the context of Express. They're the exact same thing as middleware, and middleware and controllers are literally the same thing, it's just the intent.
[00:00:34] So controllers are meant to return some data from somewhere. And in our case, it's gonna be from our database using our models. But they could return data from somewhere else. If you have a microservice architecture, your controllers might talk to another microservice, or they might talk to some third party library or Stripe or whereever.
[00:00:51] They're gonna be returning data from some resource. And if they're not, then why are they on your API? What are they doing? So most likely it's gonna be returning some data, some information from a request.
>> Scott Moss: So controllers handle what a Route + Verb combo can access from the database, right?
[00:01:10] So we wrote some hello world ones, we did some generic ones. You messed around with this thing called response. You don't really kinda understand how that works, but that's how all the stuff in the controller goes together to respond to what a Route + Verb combo. So slash user, GET request, we write a controller for that.
[00:01:28] Slash item, PUT request, we write a controller for that. So each one of those combinations has its own controller that does a job.
>> Scott Moss: So like I said, think of them as the final middleware in the stack for a request. There is no intent to proceed to another middleware function after a controller.
[00:01:49] Once you get to a controller, your intent is, I'm done. I'm not gonna call next here, cuz this is the final middleware. The only time I could ever see myself calling next inside of a controller is, again, it's the same case in the middleware, is if you have error handler somewhere at the end of your routing that's gonna handle all errors.
[00:02:06] So if you have an error in your controller, you call next, and you pass an error, and you delegate to that error handler. Other than that, you will never call next inside of a controller, because then it's just middleware. So, yeah, just remember, it's just gonna be finalized there.