In this section we will SPRINGCLEAN! ✨
You can download the end product from my github! Click here!
i.e make our code more organized!
to note we have not talked about data we're receiving and if we're able to 'get' it back (next up!)
So now we have completed a basic setup, let's try to upgrade our setup where if our server grows (ie we have a lot of routes) we will not be lost in code!
Right now with the basic set up, all the routes are stored in 'server.js', however what if we start creating a lot of routes...
The server.js file would be so crowded with code!
So in order to avoid this, we will now introduce ✨ MVC Code Organization! ✨
MVC Code Organisation
What is MVC?
MVC (Model-View-Controller) is a design pattern commonly used in web development to organize code and separate concerns within an application.
1. Model
- The Model represents the data and business logic of the application. It encapsulates the data and defines the rules for manipulating that data.
- Typically, models are responsible for tasks such as interacting with the database, performing data validation, and implementing business logic.
- Models are independent of the user interface and do not contain any presentation logic.
2. View
- The View is responsible for presenting data to the user and handling user interactions.
- It represents the user interface of the application, including HTML templates, CSS stylesheets, and client-side JavaScript.
- Views receive data from the controller and render it to the user in a format that is suitable for presentation.
3. Controller
- The Controller acts as an intermediary between the Model and the View.
- It receives input from the user, processes it, interacts with the Model to perform the necessary actions, and then selects an appropriate View to render the response.
- Controllers handle incoming requests, retrieve data from the Model, and pass that data to the View for rendering.
- They contain the application's business logic for handling requests and coordinating interactions between the
MVC & Express
Express, as it states on its landing page, is unopinionated. This means we are free to structure and organize our Express apps anyway we please.
In fact, many web frameworks such as Ruby on Rails, ASP.net, Spring MVC (Java), and others implement the MVC architectural pattern.
Accordingly, most Express developers use MVC to organize their Express applications as well...
MVC in Summary
- Routes (additional cos we're OCD 😝): contains all the database collection specific routes
- Controllers: contains all the functions (actions) that will be executed when the routes get called
- Models: contains all the schemas (related to database! we will touch on this later)
🎀 Let's Begin to add a Routes and Controllers to our express app!
🎀
Creating ✨Routes
✨ 🎀
1) Create routes
folder
mkdir routes
cd routes
touch <name-of-database-collection>Router.js
What shall we name the route file? Let's say I am creating a website for bookings.
We would have Users and Bookings, these 2 would belong to 2 database collection (but in bruno you can store it under 1 collection (that's just their naming) ie your project name and then have different folders for different groups of data).
Data eventually could be linked but for now let's not care about that.
2) Create specific routes file
In this situation, i will name the files in routes
- bookingRouter
- userRouter
in this folder we will store all the config for the different routes
2.1) the specific route file
// 1) import the router
var express = require('express');
var router = express.Router();
// 2) use router.get() ... instead of app.get() ...
router.get('/user', function (req, res) {
res.send('Here is all your bookings!');
});
// 3) export the router
module.exports = router;
2.2) update the server.js file
this is so that we can get the routes we 'extracted' away from server.js
// import the routes
var bookingRouter = require('./routes/bookingRouter');
var userRouter = require('./routes/userRouter');
// use the routes
app.use('/booking', bookingRouter);
app.use('/user', userRouter);
REMEMBER TO RESTART YOUR SERVER IF YOU'RE NOT USING NODEMON!
You can now try to use Bruno to ping the endpoints! Your endpoints should still work!
Creating ✨Controllers
✨ 🎀
Now, our code is still 'kinda' messy. You might not see it now but what if the code below contains more lines?
router.get('/user', function (req, res) {
// even
// more
// lines
// here
res.send('Here is all your users!');
});
if it gets too long, the routes folder would hold not only the routing
data but also data logic!
which preferably we would like different responsibilites to be separated.
As such, we will 'move out' the logic into a Controllers folder / file
.
1) Create Controllers
folder
DOUBLE CHECK THAT YOU ARE IN THE PROJECT FOLDER AND NOT ROUTES FOLDER
mkdir controller
cd controller
touch <name-of-database-collection>Controller.js
2) Create specific controller file
In this situation, i will name the files in routes
- bookingController
- userController
in this folder we will store all the config for the different controllers
2.1) the specific controller file
const getUsers = function (req, res) {
// even
// more
// lines
// here
res.send('Here is all your users!');
};
module.exports = { getUsers };
2.2) update the specific route file (since we took out the logic)
// require the controller we made
const userController = require('../controllers/userController');
// update the function
router.get('/user', userController.getUsers);
AND WE'RE DONE!