Lee
Lee

Reputation: 2992

Node.JS - Express: Coding style

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?

Upvotes: 2

Views: 820

Answers (4)

Narendran
Narendran

Reputation: 735

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
}

Upvotes: 0

Tamer Aktaş
Tamer Aktaş

Reputation: 425

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..}
})

Upvotes: 0

MattTannahill
MattTannahill

Reputation: 616

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

Upvotes: 2

Gandalf the White
Gandalf the White

Reputation: 2465

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);  

Upvotes: 1

Related Questions