this call controller in routes file 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 can see end result of resolved callback above hits res.jsonsuccess , reject (the 2nd param in then function) hits res.jsonfail.
res.jsonsuccess & res.jsonfail custom middlewares project , format , log data accordingly.
my question:  want simplify further. possible pass 1 parameter then() handle both resolve , reject? 
for example
router.post('/create-user', function(req, res) {         createusercontroller.createuser( req.body.username, req.body.username ).then( res.jsonoutdecide ); }); based on accepted answer able put following middleware:
    /**  * unify json output of response jsonfail , 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 promise , passes onto success or fail options above          * @param p          * @returns {*}          */         res.jsonpromise = function(p) {             return p.then(res.jsonsuccess, res.jsonfail);         };          next();     }; }; which can used in routes file uses prmoise based controller eg:
router.get('/get-all', function(req, res) {     res.jsonpromise( createusercontroller.getallusers( ) ); }); 
is possible pass 1 parameter
then()handle both resolve , reject?
no.
what want instead define function can pass promise to:
function jsonpromise(res, p) {     return p.then(res.jsonsuccess, res.jsonfail); } so can do
router.post('/create-user', function(req, res) {     jsonpromise( res, createusercontroller.createuser( req.body.username, req.body.username ) ); }); even more elaborate take whole promise-returning function , decorate it:
function jsonresponse(f) {     return function(req, res) {         promise.resolve(req).then(f).then(res.jsonsuccess, res.jsonfail);         // similar `f(req).…`, catching exceptions , allowing plain return values     }; } router.post('/create-user', jsonresponse(function(req) {     return createusercontroller.createuser( req.body.username, req.body.username ); })); 
Comments
Post a Comment