Created
February 8, 2016 21:41
-
-
Save sebyx07/306465253092f325337e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import DS from 'ember-data'; | |
const pako = window.pako; | |
import { | |
AdapterError, | |
InvalidError, | |
TimeoutError, | |
AbortError | |
} from 'ember-data/-private/adapters/errors'; | |
import EmptyObject from "ember-data/-private/system/empty-object"; | |
export default DS.RESTAdapter.extend({ | |
ajax: function(url, type, options) { | |
const adapter = this; | |
return new Ember.RSVP.Promise(function(resolve, reject) { | |
const hash = adapter.ajaxOptions(url, type, options); | |
hash.success = function(payload, textStatus, jqXHR) { | |
payload = uncompressToJSON(payload); | |
let response = adapter.handleResponse( | |
jqXHR.status, | |
parseResponseHeaders(jqXHR.getAllResponseHeaders()), | |
payload | |
); | |
if (response instanceof AdapterError) { | |
Ember.run.join(null, reject, response); | |
} else { | |
Ember.run.join(null, resolve, response); | |
} | |
}; | |
hash.error = function(jqXHR, textStatus, errorThrown) { | |
let error; | |
if (!(error instanceof Error)) { | |
if (errorThrown instanceof Error) { | |
error = errorThrown; | |
} else if (textStatus === 'timeout') { | |
error = new TimeoutError(); | |
} else if (textStatus === 'abort') { | |
error = new AbortError(); | |
} else { | |
error = adapter.handleResponse( | |
jqXHR.status, | |
parseResponseHeaders(jqXHR.getAllResponseHeaders()), | |
adapter.parseErrorResponse(jqXHR.responseText) || errorThrown | |
); | |
} | |
} | |
Ember.run.join(null, reject, error); | |
}; | |
hash.dataType = undefined; | |
Ember.$.ajax(hash); | |
}, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); | |
} | |
}); | |
function parseResponseHeaders(headerStr){ | |
var headers = new EmptyObject(); | |
if (!headerStr) { return headers; } | |
const headerPairs = headerStr.split('\u000d\u000a'); | |
for (var i = 0; i < headerPairs.length; i++) { | |
const headerPair = headerPairs[i]; | |
// Can't use split() here because it does the wrong thing | |
// if the header value has the string ": " in it. | |
const index = headerPair.indexOf('\u003a\u0020'); | |
if (index > 0) { | |
const key = headerPair.substring(0, index); | |
headers[key] = headerPair.substring(index + 2); | |
} | |
} | |
return headers; | |
} | |
function uncompressToJSON(data){ | |
let compressData = atob(data); | |
compressData = compressData.split('').map(function(e) { | |
return e.charCodeAt(0); | |
}); | |
const binData = new Uint8Array(compressData); | |
data = pako.inflate(binData); | |
return JSON.parse(String.fromCharCode.apply(null, new Uint16Array(data))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment