Skip to content

Instantly share code, notes, and snippets.

@yzarubin
Last active August 29, 2015 14:16
Show Gist options
  • Save yzarubin/20df0cc92810b2ad67d4 to your computer and use it in GitHub Desktop.
Save yzarubin/20df0cc92810b2ad67d4 to your computer and use it in GitHub Desktop.
Creating robust promise-based controllers with X-Error
var buildCtrl = function(promiseFn){
return function(req, res) {
promiseFn(req)
.then(function(data){
res.json(200, data);
}, function(e){
res.status(e.httpCode || 500)
.send(e.httpResponse || 'Internal error');
});
};
};
// User API
var user = {
find: function(req){
return User.find(req.params.id)
.then(function(user){
if (!user) throw new XError(1000).hc(400).hr('User not found').d(req.params.id);
return user;
});
},
create: function(req){
return User.create(req.body)
.then(null, function(e){
throw XError(1001, e).hc(400).hr('Unable to create user').d(req.body);
});
}
};
app.get('/user/:id', buildCtrl(user.find));
app.post('/user', buildCtrl(user.create));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment