I am using node.js and expressing my current application. I created several intermediate functions, each of which is created as follows:
function loadUser(req, res, next){ ... }
I would like to create middleware that checks for the presence of required parameters in a expressed action. For example, I have an action / user / create, which requires an alias, password, email, ... as required parameters. Then I need to pass this parameter list to the middleware so that it can check if these parameters exist in req.query.
Any idea?
UPDATE
I finally did the following (in the express documentation there is an example of middleware that requires the additional parameter http://expressjs.com/guide.html#route-middleware ).
function checkParams(arr){ return function(req, res, next) { // Make sure each param listed in arr is present in req.query var missing_params = []; for(var i=0;i<arr.length;i++){ if(! eval("req.query." + arr[i])){ missing_params.push(arr[i]); } } if(missing_params.length == 0){ next(); } else { next(JSON.stringify({ "error" : "query error", "message" : "Parameter(s) missing: " + missing_params.join(",") })); } } }
Then it is called as other averages:
app.post('/user/create', checkParams(["username", "password"]), function(req, res){ ... });
source share