Skip to content

Commit

Permalink
Merge pull request #139 from KleeGroup/net-err
Browse files Browse the repository at this point in the history
[network] Add the fetch config and errors handling.
  • Loading branch information
pierr committed Jun 19, 2015
2 parents 9699ecf + d4f556e commit 95652d9
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
30 changes: 30 additions & 0 deletions network/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
let merge = require('lodash/object/merge');
let {isObject, clone} = require('lodash/lang');

/**
* Configuration object.
* @type {{CORS: boolean}}
*/
let configuration = {
CORS: true,
xhrErrors: {}
};

/**
* Function which overrides the configuration.
* @param conf
*/
function configure(conf){
if(isObject(conf)){
merge(configuration, conf);
}

}


module.exports = {
configure: configure,
get(){
return clone(configuration);
}
};
8 changes: 7 additions & 1 deletion network/fetch.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ var cancellablePromiseBuilder = require('./cancellable-promise-builder');
var uuid = require('uuid').v4;
var dispatcher = require('../dispatcher');


/**
* Create a pending status.
* @return {object} The instanciated request status.
Expand Down Expand Up @@ -46,6 +47,7 @@ function fetch(obj, options) {
};
var request = createCORSRequest(obj.method, obj.url, options);
var requestStatus = createRequestStatus();
var config = require('./config').get();
if (!request) {
throw new Error('You cannot perform ajax request on other domains.');
}
Expand All @@ -59,9 +61,13 @@ function fetch(obj, options) {
//Request success handler
request.onload = function () {
var status = request.status;
if (status !== 200) {
var err = JSON.parse(request.response);
if (status < 200 || status >= 300 ) {
var err = JSON.parse(request.response);
err.statusCode = status;
if(config.xhrErrors[status]){
config.xhrErrors[status](request.response);
}
updateRequestStatus({id: requestStatus.id, status: 'error'});
failure(err);
}
Expand Down
3 changes: 2 additions & 1 deletion network/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@ module.exports = {
cors: require('./cors'),
fetch: require('./fetch'),
cancellablePromiseBuilder: require('./cancellable-promise-builder'),
builtInStore: require('./built-in-store')
builtInStore: require('./built-in-store'),
config: require('./config')
};

0 comments on commit 95652d9

Please sign in to comment.