NodeJS API-Part 5 / Model/Router/Controller structure
This is the 5º tutorial of a complete series of building a production “NodeJS API using Express, MySQL and Sequelize”.
Full source code of this class is available at GitHub Martial Arts API Part 5
UNDERSTANDING THE PROBLEM
Our project is not too big, but we already have 36 lines and a single endpoint. In a real application where we could have +100 endpoints our app.js
would be a really mess.
To avoid that we will structure our app in Models/Controllers/Routes. In the most informal way these will mean.
Model: A representation of our table columns.
Routes: This will tell our application, “If the user is requesting a POST request we will do this…, if the user is requesting a GET request we will do that…”
Controllers: Where we implement logic and send the response.
CREATING YOUR FOLDERS/FILES
Create the folders and files, as the picture shows:
- api
- controllers
- dojos.js
- models
- dojos.js
- routes
- dojos.js
ADD THE CODE TO THE FILES
controllers/dojos.js
The controller will contain the code which you are going to send to the user. In my case it will have a method called getAll()
which receives two parameters (the req and res) and returns our JSON fake data to the user.
Do not forget to wrap all methods in module.exports
so you can use it latter in the other files.
routes/dojos.js
The router is going to be the bridge between app.js and the controllers. It just basically tells, for the get
request execute this method that is inside the controller, for the post
request execute that method that is inside the controller.
Do not forget to export the router, so you can use in your app.js
file.
app.js
Now, the logic of our API will be in our controllers, thefore there is nothing left for app.js
. We will dismiss all those lines that was responsible for returning the JSON object we will basically tell, “just use this router for this endpoint and we are ready to go.”
const dojosRoutes = require("./api/routes/dojos");...app.use("/dojos", dojosRoutes);
CONCLUSION
Look at the drawing again and you will understand what is happening here!
Full source code of this class is available at GitHub Martial Arts API Part 5