I'm building a REST-api and have rendering function that looks like this:
render = (req, res) => {
var output = {},
async = [],
detailed;
if(req.user){
detailed = req.user.obj.detailed();
async.push(detailed);
}
if(Object.keys(req.query).length){
output.params = req.query;
}
if(req.validationErrors().length > 0 ){
output.errors = req.validationErrors();
}
sequelize.Promise.all(async).then((response) => {
if(response.length > 0){
output.user = response[0];
}
res.json(output);
});
};
It grabs stuff and ouputs it like a JSON. It's usually run as the last function in any request:
app.all('/user/me', auth, render);
In the app I also validate input data at different stages. If the input fails, I want to go straight to the rendering. In order to avoid passing around req/res all over the place, I would like to somehow go to that routing, rather than calling the function, like I am now, is that possible? I can't use next, because sometimes there are more than one function left.
validate = (tests) =>{
req.assert(tests);
//Go to render if validation fails.
//req,res
if (req.validationErrors().length) {
return render(req, res);
}else{
return true;
}
};
You could hook up some Error-handling middleware that runs your standard render method. Then your route validations would need to generate an error.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments