'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _promise = require('babel-runtime/core-js/promise');

var _promise2 = _interopRequireDefault(_promise);

var _error = require('../constants/error');

var errorConstants = _interopRequireWildcard(_error);

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Helper method for sending an http requests.
 * @param {string} verb - HTTP verb to be used in request. E.g. GET, POST, PUT.
 * @param {string} uri - The uri to send the request to.
 * @param {string} body - json string of the body.
 * @returns {Promise} request promise that resolves to the HTTP response.
 */
var httpRequest = function httpRequest(verb, uri) {
  var body = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null;

  var httpRequest = new XMLHttpRequest();
  return new _promise2.default(function (resolve, reject) {
    try {
      httpRequest.open(verb, uri, true);
      if (body) {
        httpRequest.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
      }
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState === 4) {
          var _body = null;
          try {
            _body = JSON.parse(httpRequest.responseText);
            // eslint-disable-next-line no-unused-vars
          } catch (err) {}
          resolve({
            body: _body,
            status: httpRequest.status
          });
        }
      };
      httpRequest.send(body);
    } catch (err) {
      reject(errorConstants.REQUEST_FAILED(err));
    }
  });
};

exports.default = httpRequest;
//# sourceMappingURL=httpRequest.js.map