2

I'm writing some rest API with Node.JS and Express. So for each API, I'd need to do all the usual stuff like parameter validation, authentication, authorization and then the actual business logic. Some sodo code to illustrate this:

router.get('/users', function (req, res){
    async.auto(
        authenticateCaller();
        authorizeCaller();
        validateParams();

        doGetUsers(); 
    )
})

This style certainly works but it makes the whole function very cumbersome by including a lot of extra pre-purpose codes. I know in web app programming, MVC has been introduced to separate UI, Module and Controller into different code groups, which is much cleaner. Is there any similar framework that can be helped to achieve this purpose?

0

4 Answers 4

2

Use middleware. Middleware is just a function that takes in three parameters:

function (req, res, next) {}

Call router.use() to register middleware before defining any routes. This will cause that middleware to be called before every route is executed.

These are all functions of middleware:

  • authenticateCaller();
  • authorizeCaller();
  • validateParams();

http://expressjs.com/en/guide/using-middleware.html

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Matt. This is the fundamental thing I'm missing.
1

This is what I do.

Using Routes for Node.js Here I am making way for a folder named routes that has all the codes in it.

var routes = require('./routes');
var route_add_user = require('./routes/add_user');

Calling the function with the route here; .adduser is function name within that js file

 app.get('/adduser', route_add_user.adduser);  

Comments

0

define a function do your routine jobs

 fuction auth(res,req,next){
     authenticateCaller();
    req.isAuthorized = authorizeCaller();
     validateParams();
     next();
    }

 router.get('/users',auth);
 router.get('/users', function (req, res){
   if( req.isAuthorized)
   {..do some stuff here..}
})

Comments

0

This is one of the STYLE i was following to authenticate and use the API in express framework.

register.js
-----------
exports.addUser = function(req, res) { 
    // do something
};
exports.deleteUser = function(req, res) { 
    // do something
};

routes.js
---------
var register = require('./register');
router.get(‘/register’,auth, register.addUser);
router.get(‘/deleteUser’,auth, register.deleteUser);
// Better make it separate common file to reuse all the API
function auth(req,res,next) { 
   // do something to authenticate your API
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.