amatiasq
4/16/2014 - 1:38 PM

http-request.js

(function(global) {
  'use strict';
  
  function chain(obj, method) {
    var original = obj[method];
    obj[method] = function() {
      original.apply(this, arguments);
      return this;
    };
  }
  
  function HttpRequest() {
    var xhr = new XMLHttpRequest();
    chain(xhr, 'open');
    chain(xhr, 'setRequestHeader');
  
    var send = xhr.send;
    xhr.send = function(data) {
      var self = this;
      return new Promise(function(resolve, reject) {
        self.addEventListener('readystatechange', function(event) {
          if (self.readyState === XMLHttpRequest.DONE)
            resolve(self);
        });
        send.apply(self, arguments);
      });
    };
  
    return xhr;
  }
  
  global.HttpRequest = HttpRequest;
})(this);
(function(global) {
  'use strict';
  var count = 0;

  function jsonp(url, options) {
    return new Promise(function(resolve, reject) {
      var separator = url.indexOf('?') !== -1 ? '&' : '?';
      var callback = '__mq_callback__' + count;

      count++;
      url += separator + 'callback=' + callback;

      var tag = document.createElement('script');
      tag.setAttribute('type', 'text/javascript');
      tag.setAttribute('src', url);
      document.head.appendChild(tag);

      window[callback] = function(response) {
        delete window[callback];
        document.head.removeChild(tag);
        resolve(response);
      };

      if (options && options.timeout) {
        setTimeout(function() {
          reject(new Error('Request timeout'));
        }, options.timeout);
      }
    });
  }

  global.HttpRequest.jsonp = jsonp;
  
})(this);
function ajax() {
  return new HttpRequest()
    .open('POST', '/something.php')
    .setRequestHeader('Content-Type', 'text/plain')
    .send('Hello')
    .then(function(request) {
      return request.responseText;
    });
}

function jsonRequest(data) {
  return new HttpRequest()
    .open('POST', '/something.php')
    .setRequestHeader('Content-Type', 'text/json')
    .send(JSON.stringify(data))
    .then(function(request) {
      return JSON.parse(request.responseText);
    });
}