Skip to content

Instantly share code, notes, and snippets.

@ericraio
Created March 5, 2015 23:22
Show Gist options
  • Select an option

  • Save ericraio/de51bbb588ba52f84ed5 to your computer and use it in GitHub Desktop.

Select an option

Save ericraio/de51bbb588ba52f84ed5 to your computer and use it in GitHub Desktop.
define(['jquery', 'lib/appcontext', 'lib/exceptions'],function(jquery, app, errors){
'use strict';
var XhrTransport = function(){
this.initialize();
};
XhrTransport.prototype = {
initialize: function() {
// just for testing the construction
},
get: function(url, data, headers) {
return this.send('GET', url, data, headers);
},
post: function(url, data, headers) {
return this.send('POST', url, data, headers);
},
getAuthHeaders: function() {
var token = app.getAccessToken();
return token ? {
'Authorization' : 'Bearer ' + token
} : {};
},
send: function(method, url, data, headers) {
var self = this;
var deferred = new jQuery.Deferred();
headers = jQuery.extend({}, this.getAuthHeaders(), headers);
var hasQueryString = (method === 'GET');
var ajaxPromise = jQuery.ajax({
type: method,
headers: headers,
data: hasQueryString ? data : JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
crossDomain: true,
url: url,
processData: hasQueryString
});
ajaxPromise.always(function(xhrResult, statusText, statusObject) {
var xhr = 'status' in xhrResult ? xhrResult : statusObject;
var data;
try {
data = JSON.parse(xhr.responseText);
} catch(e) {
data = null;
}
var exception;
var result = {
data: data,
headers: null
};
if (!result.data) {
// uncought API error or network problem
xhr.requestUrl = url;
exception = self.handleError(xhr);
// reject with CriticalError exception, this is a transport failure
return deferred.reject(exception);
}
// move API errors to own namespace
if (result.data.errors) {
result.errors = result.data.errors.map(function(error){
// normalize
return {
code: error.code || 'UNKNOWN',
message: error.message || null
};
});
result.data = null;
result.errors.url = url;
// it's an error but it's not a transport error so normalize it and resolve
return deferred.resolve(result);
}
// move API errors without code to own namespace
if (xhr.status > 399) {
result.errors = [{
code: 'API_' + xhr.status,
message: null
}];
result.data = null;
result.errors.url = url;
// it's an error but it's not a transport error so normalize it and resolve
return deferred.resolve(result);
}
// just good data
return deferred.resolve(result);
});
return deferred.promise();
},
handleError: function(xhr) {
var message = {
type: 'transport',
code: 'HTTP_' + xhr.status,
message: xhr.status ? xhr.statusText : 'Can\'t reach the server',
origin: xhr.requestUrl || null
}
if (xhr.status === 401) {
return new errors.AuthorizationError(message)
} else {
return new errors.CriticalError(message);
}
}
};
return XhrTransport;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment