Code Structuring. Controllers
In the previous lesson, we connected routes to our database. Now when a route receives a request, the database is examined and the user receives an answer:
// routes/users.js
const User = require('../models/user');
router.get('/:id', (req, res) => {
// search the database
User.findById(req.params.id)
// return the found data to the user
.then(user => res.send({ data: user }))
// if the record was not found, display an error message
.catch(err => res.status(500).send({ message: 'Error' }));
});
router.post('/', (req, res) => {
const { name, about } = req.body;
User.create({ name, about })
.then(user => res.send({ data: user }))
.catch(err => res.status(500).send({ message: 'Error' }));
});
// and so on
Save
If you're using a lot of routes, they tend to get lost in the code. For convenience, we'll divide the code into two files: a controller file and a routes file. We'll also put the controller file into a separate folder named controllers.
// controllers/users.js
// this file is the user controller
const User = require('../models/user');
// the getUser request handler
module.exports.getUser = (req, res) => {
User.findById(req.params.id)
.then(user => res.send({ data: user }))
.catch(err => res.status(500).send({ message: 'Error' }));
};
// the createUser request handler
module.exports.createUser = (req, res) => {
const { name, about } = req.body;
User.create({ name, about })
.then(user => res.send({ data: user }))
.catch(err => res.status(500).send({ message: 'Error' }));
};
Save
// routes/users.js
// this is the routes file
const { getUser, createUser } = require('../controllers/users');
// route definitions
router.get('/:id', getUser)
router.post('/', createUser);
Save
A controller is a collection of request handler functions responsible for interacting with a particular model (in this case, the User model). These handler functions can read, create, update, and delete documents, and send a response back to the client.
While the routes file defines the routes themselves, it passes off the actual handling of the request to the controller files, which is why the functions inside the controller are called "request handlers" or just "controller functions".
In Express, each request handler is often the last middleware executed, because instead of calling next(), it returns an answer to the user.
The controller file describes the logic of request processing, and the routes file determines when this logic should be applied depending on the requested path and HTTP method.
Comments