Javascript ajax library supporting global events -
which ajax library should use react/flux app? need globally handle errors (e.g. automatically logout , redirect login if 401; similar $http service in angular) , use promises.
the way i'm doing combination of 3 libraries:
webutils.js
var promise = require('bluebird'); module.exports = { makeapicall: function() { return promise.resolve($.get("http://makeyourapicall")); } };
actions.js:
var reflux = require('reflux'); var webutils = require('web-utils.js'); var actions = reflux.createactions({ getdatafromserver: { asyncresult: true } }); actions.getdatafromserver.listenandpromise(webutils.makeapicall); module.exports = actions;
explanation:
- the
asyncresult: true
increateactions
call creates "nested/asynchronous action" can listen to. more here - the
listenandpromise
function hooks promise nestedcompleted
,failed
callbacks based on result
you can consume nested actions this:
actions.getdatafromserver.complete.listen(res => console.log('success', res)); actions.getdatafromserver.failed.listen(err => console.log('failed', err));
in sense can implement universal error handler hooking .failed
events.
reflux-error-handler.js
var _ = require('lodash'); var reflux = require('reflux'); var notificationstore = require('../stores/notificationstore'); /** * overall error handler async actions * @param err */ function handleerror(err) { console.error('encountered error:', err); notificationstore.createerrornotification(err); } /** * loops on refluxactions , attaches error handler async actions * @param refluxactions {object} hash of reflux actions ot generate * @constructor */ var refluxerrorhandler = function(refluxactions) { _.foreach(refluxactions, func => { if(func.failed) { func.failed.listen(handleerror); } }); return refluxactions; }; module.exports.wraprefluxactions = refluxerrorhandler;
to use in actions.js:
var reflux = require('reflux'); var webutils = require('web-utils.js'); var refluxerrorhandler = require('reflux-error-handler.js'); var actions = reflux.createactions({ getdatafromserver: { asyncresult: true } }); actions.getdatafromserver.listenandpromise(webutils.makeapicall); module.exports = refluxerrorhandler(actions);
Comments
Post a Comment