Wednesday, 12 April 2017

How to use single piece of middleware for more than one express router?

I am working on a university project and we have decided to go for MEAN technology stack. To be honest I am a beginner with NodeJS and express, more precisely this is the first time I do sth with it. I've found that is preferable to use express.Router rather than putting all routes to express instance e.g. app.post('path', function(req, res) { ... })

So this is what I have

var express = require('express');
var app = express();

function authorizationMiddleware(req, res, next) {
...
}

// handles login, doesn't meed autorizationMiddleware
var authRouter = express.Router();
authRouter.route('/login')
    .post(function (req, res) {
    ...
    });

// handles fetching of a single, all person(s), fetching of transactions for a person
var personRouter = require('./routes/personRoutes')(Person, Transaction, autorizationMiddleware);
//handles adding of a new transaction e.g. POST /api/transactions where params such as sender, recipient and amount are passed in body
var transactionRouther = require('./routes/transactionRoutes')(Person, Transaction, autorizationMiddleware);

app.use('/api', authRouter);
app.use('/api/persons', personRouter);
app.use('/api/transactions', transactionRoutes);

app.listen(8080, function () {
    console.log('Listening on port: ' + 8080);
});

As you can see I have three routers (not even sure if I have gonne too far with them), authRouter is handling login only and I have also decided to separate persons from transactions (maybe I could have sth like /api/persons/:personId/transactions to create new transaction but I rather liked the idea of sending all required params in body).

I would like to ask if you agree with the solution I tried. As you can see I am passing authrizationMiddleware function to router modules and using it there. Is there maybe a better way to handle the authorization of multiple routers with a single middleware? Could someone confirm is this a legit way to go or not? Thx in advance Cheers!



via amsalk

No comments:

Post a Comment