Skip to content

Instantly share code, notes, and snippets.

@zxqx
Created October 28, 2014 19:38
Show Gist options
  • Save zxqx/6473c230a38935e1f2e7 to your computer and use it in GitHub Desktop.
Save zxqx/6473c230a38935e1f2e7 to your computer and use it in GitHub Desktop.
module.exports = CSTransport;
var Promise = require('bluebird');
var HttpTransport = require('http-transport');
var jsonpClient = require('jsonp-client');
var path = require('path');
var urlUtil = require('url');
function CSTransport()
{
this.httpTransport = new HttpTransport();
}
CSTransport.prototype.get = function(url, params)
{
if (isExternalRequest(url)) {
return jsonpGet(url, params);
}
else {
return this.httpTransport.get(url, params);
}
};
function jsonpGet(url, params)
{
url = path.join(url, urlUtil.format({ query: params }));
url = addCallback(url);
return new Promise(function(resolve, reject) {
jsonpClient(url, function(err, data) {
if (!err)
resolve({ body: data });
else
reject(err);
});
});
}
function addCallback(url) {
// The URL already has a callback
if (url.match(/callback=[a-z]/i)) {
return url;
}
return url + ('&callback=cb' + Math.random()).replace('.', '');
}
function isExternalRequest(url)
{
return (url.indexOf('http') >= 0) ? true : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment