Reputation: 523
In express.js when we call
app.get(function(req,res){...}),
the function automatically receives request and response objects and we can give any name to function parameters like req,res or re,rs and many others.
I want to create a function that will rest in an object. When I want to use this function it must receive default arguments which may be e.g simple int 4,3 and I must be able to specify parameter names as per my choice.And these arguments must be assigned to parameter names I have defined and I must be able to use those name in code inside function.
How can I achieve this?
Upvotes: 1
Views: 49
Reputation: 523
I have found the solution myself.
It was all related to call back functions and passing the function definition to another function.
var app={
get:function(callback){
callback('Request object..','Response object..');
}
};
app.get(function(rq,rs){
console.log(rq,rs);
});
Here we can pass function definition in get
method with parameters of your own choice that's what I wanted to know.
It is not necessarily express object or methods. app can be any object and get can be any method of app. With of course parameters not necessarily req and res objects.
Upvotes: 0
Reputation: 23049
You can write your own middleware for this. For example this is how I control the mandatory fields in requests :
router.post('/relations', controlBodyMiddleware(['userIdReceiver']), relation.create);
While you can have method like this :
controlQueryMiddleware(fields) {
return function(req, res, next){
if (!req.body.mandatoryField || req.body.mandatoryField !== 5){
return next(new Error('I want mandatoryField equal to 5'));
}
req.body.myFieldAccessibleInNextMiddleware = 'Yes, this would be there';
next();
};
}
Upvotes: 1