From 00cd9daf99c695ff515c13d233569e2f0dff9fcb Mon Sep 17 00:00:00 2001 From: Max Lynch Date: Thu, 2 Jul 2015 08:53:58 -0500 Subject: [PATCH] feat(net): jsonp --- ionic/net/http.js | 77 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 76 insertions(+), 1 deletion(-) diff --git a/ionic/net/http.js b/ionic/net/http.js index d084d0c5f1..d91cce6f86 100644 --- a/ionic/net/http.js +++ b/ionic/net/http.js @@ -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); + } + } /**