This is the call to a controller in a routes file from a nodejs application running express witha promise based api.
router.post('/create-user', function(req, res) {
CreateUserController.createUser( req.body.username, req.body.username ).then( res.jsonSuccess, res.jsonFail );
});
As you can see the end result of a resolved callback above hits res.jsonSuccess and the reject (the 2nd param in the then
function) hits the res.jsonFail.
res.jsonSuccess & res.jsonFail are custom middlewares for this project and simply format and log data accordingly.
My question: I want to simplify this further. Is it possible to pass one parameter to the then()
that could handle both the resolve and reject?
For example
router.post('/create-user', function(req, res) {
CreateUserController.createUser( req.body.username, req.body.username ).then( res.jsonOutDecide );
});
Based on the accepted answer i was able to put together the following middleware:
/**
* unify the json output of any response with jsonFail and jsonSuccess methods
*/
module.exports = function(){
return function(req, res, next) {
/**
* Error json output
* @param errObj (optional)
* @returns {*}
*/
res.jsonFail = function ( errObj ) {
errObj = errObj || {};
return res.json({
success : false,
error : errObj
})
};
/**
* Success json output
* @param data
* @returns {*}
*/
res.jsonSuccess = function ( data ) {
data = data || {};
return res.json({
success: true,
data: data
});
};
/**
* Accepts a promise and passes onto the success or fail options above
* @param p
* @returns {*}
*/
res.jsonPromise = function(p) {
return p.then(res.jsonSuccess, res.jsonFail);
};
next();
};
};
Which can now very easily be used in a routes file which uses a prmoise based controller eg:
router.get('/get-all', function(req, res) {
res.jsonPromise( CreateUserController.getAllUsers( ) );
});