feat(net): jsonp

This commit is contained in:
Max Lynch
2015-07-02 08:53:58 -05:00
parent b9ca4e1340
commit 00cd9daf99

View File

@ -1,6 +1,11 @@
import * as util from 'ionic/util';
//TODO(mlynch): surely, there must be another way, sir?
window._jsonpcallbacks = {
counter: 0
};
/**
* The Http class makes it easy to send GET/POST/PUT/DELETE/PATCH requests
* and send/receive JSON (or anything else) through a simple API.
@ -38,6 +43,49 @@ export class Http {
});
}
static jsonp(url, callbackId, options) {
return new Promise((resolve, reject) => {
var script = document.createElement('script');
script.src = url;
script.async = true;
script.type = 'text/javascript';
var callback = (event) => {
script.removeEventListener('load', callback);
script.removeEventListener('error', callback);
document.body.removeChild(script);
let text, status;
if(event) {
if(event.type === "load" && !window._jsonpcallbacks[callbackId].called) {
event = { type: "error" };
}
text = event.type;
status = event.type === "error" ? 404 : 200;
resolve(window._jsonpcallbacks[callbackId].data, status, text);
} else {
reject();
}
/*
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
callbackId, function(status, text) {
completeRequest(callback, status, callbacks[callbackId].data, "", text);
callbacks[callbackId] = noop;
});
*/
};
script.addEventListener('load', callback);
script.addEventListener('error', callback);
document.body.appendChild(script);
return callback;
});
}
static _method(method, url, data, options, sendsJson) {
options = util.defaults(options, {
method: method,
@ -54,7 +102,34 @@ export class Http {
options.headers['Content-Type'] = 'application/json';
}
return Http.fetch(url, options);
if(options.method == 'jsonp') {
// Adopted from Angular 1
let callbacks = window._jsonpcallbacks;
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
console.log('CALLBACK DATA', data);
callbacks[callbackId].data = data;
callbacks[callbackId].called = true;
};
console.log('Set up callbacks', callbacks);
/*
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
callbackId, function(status, text) {
completeRequest(callback, status, callbacks[callbackId].data, "", text);
callbacks[callbackId] = noop;
});
*/
url = url.replace('JSON_CALLBACK', '_jsonpcallbacks.' + callbackId);
return Http.jsonp(url, callbackId, options);
} else {
return Http.fetch(url, options);
}
}
/**