Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

5. Router, Middleware, MVC

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Router, Middleware, MVC

Table of Content –
1. Router.
2. MVC Architecture.
3. Middleware.

1. Router –
Using expressJS we can create routes. Routes helps us to segregate our each routes. For
example there can be one route called as authentication inside which we will specify our
auth routes for login, logout, signin and signout. We are segregating all of the routes so
that we will not flood the index.js file. So in order to segregate routes, we can first
create a folder called routes and then for example create a post route –

//post.route.js
const router = require('express').Router();

router.get("/user", (req, res) => {


res.status(200).json({
id: '123423',
title: 'demo title',
imgUrl: "https://dsalfkjsdaflldsafl.com"
});
});

module.exports = router;

After exporting the router, we will go back to index.js file and then do `app.use()` after
the `app.get()` route. `app.use()` is a middleware. Inside `app.use()` function we will
define our route and then the path of our route:
//index.js
const postRouter = require('./routes/post.routes');
//..and all the default codes..

app.get("/", (req, res) => {


res.status(200).json({
status: "Ok"
});
});

app.use('/post', postRouter);
//.. any other routes more than one..

For now there can be only one or two routers, but in future we will have a lot of routers,
and then our index.js file will start flooding, so, we can go even higher while segregating
our routes.
So inside routes folder we will create a folder called as `v1` and then create an `index.js`
file inside it, and inside the routes folder create another file `index.js`. now let us start
connecting these files with each other –

// index.js file of v1 folder


const router = require('express').Router();
const postRouter = require('./post.route');

router.use('/post', postRouter);

module.exports = router;
We have connected our post.route.js file with our index.js file which is inside v1 folder.

//index.js file of routes folder


const router = require('express').Router();
const v1 = require('./v1/index');

router.use('/v1', v1);

module.exports = router;
We have connected v1’s folder index.js file into our routes folder index.js file.
//Our root index.js file
const express = require('express');

//Our routes index.js file.


const mainRoute = require('./src/routes/index')

const app = express();

//allowing json files inside our code –


app.use(express.json());

//Using the chained routes which we just created.

app.use('/', mainRoute)

app.get('/', (req, res) => {


res.status(200).json({
message: "OK"
});
});

app.listen(3000, () => {
console.log('server started');
});
And finally we have connected routes index.js file with our root index.js file

2. MVC Architecture –
MVC (Model, View, Controller) is simply a design or architectural pattern used in
software engineering. While this is not a hard rule, but this pattern helps developers
focus on a particular aspects of their application, one step at a time. The main goal of
MVC is to split large applications into specific sections that have their own individual
purpost.
 Model – As the name implies, a model is a design or structure. In the case of
MVC, the model determines how a database is structured, defining a section of
the application that interacts with the database.
 View – View or Routes, is the page or output that we see after hitting the API.
 Controller – The controller interacts with the model and serves the response and
functionality to the view. When an end user makes a request, it’s sent to the
controller which interacts with the database.
How these three talk to each other

First we will create 2 folders on the parent directory, one will be controllers, second will be
models. Inside models folder we will, as an example, create User.js file. Inside the User.js file we
will create a dummy data for demonstration. In future we will get these data from our
MongoDB database –

//User.js
const users = [
{
name: "abc",
email: "abc@gmail.com",
password: 1234
},
{
name: "def",
email: "def@gmail.com",
password: 4321
},
];

module.exports = users;

Now inside the controllers folder we will create an auth.controller.js file and create a login
controller inside it –

const User = require('../models/User')


const loginController = async(req, res) => {
const email = req.body.email;
const password = req.body.password;

console.log(email, password);

if (!email && !password) {


return res.send('Email and Password are required.')
};

if (!email) {
return res.send('email is required.')
};

if (!password) {
return res.send('password is required.')
};

const user = User.find(item => item.email === email);

if (!user) {
return res.send('User not found');
};

if (user.password !== password) {


return res.send('password is incorrect');
};

const name = user.name;


res.json({
name
});
};

module.exports = {
loginController
};
Logic of creating login controller (as a demo only).

Now inside auth.route.js file we will use our controller –

const { loginController } = require('../../controllers/auth.controller');


const router = require('express').Router();
router.get('/login', loginController);

module.exports = router;

This is how the models, routes and controllers talk with each other and perform such elegance
work.

3. Middleware –
ExpressJS is a routing and middleware web framework that has minimal functionality of
its own. Middleware functions are functions that have access to the request object
(req), the response object (res), and the next middleware function (next) in the apps
request-response cycle. The next middleware function is commonly denoted by a
variable named next.

Middleware functions can perform the following tasks:


 Execute any code.
 Make changes to the request and the response object.
 End the request-response cycle.
 Call the next middleware function in the stack.
If the current middleware function does not end the request-response cycle, it must call
next() to pass control to the next middleware fuinciton. Otherwise, the request will be
left hanging.
The next example shows a middleware function with no mount path. The function is
executed every time the app receives a request.
We will create a middleware function like this –

// m1.js file for middleware


const m1 = (req, res, next) => {
console.log("api was called");
next();
}

module.exports = m1;
Now we will use this middleware like this –
//Inside our root index.js file
const m1 = require('./src/middlewares/m1');
//..the rest of the code of root index.js file..

app.use('/', m1, mainRoute);


We just passed the middleware function in between of the api path and the api routes.
This is how we create and use a middleware. Whenever any of the api will get hit, it will
console log saying `api was called`.

You might also like