UNPKG

2.75 kBJavaScriptView Raw
1/* global XMLHttpRequest */
2"use strict";
3
4Object.defineProperty(exports, "__esModule", {
5 value: true
6});
7
8function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
9
10var _lodash = require("lodash");
11
12var _lodash2 = _interopRequireDefault(_lodash);
13
14var _bluebird = require("bluebird");
15
16var _bluebird2 = _interopRequireDefault(_bluebird);
17
18var _errors = require("./errors");
19
20var _shared = require("./shared");
21
22var send = function send(verb, url, data) {
23 return new _bluebird2["default"](function (resolve, reject) {
24 var xhr = api.createXhr();
25 xhr.open(verb, url);
26 if (_lodash2["default"].isObject(data)) {
27 data = JSON.stringify(data);
28 xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
29 }
30 xhr.onreadystatechange = function () {
31 if (xhr.readyState === 4) {
32 (0, _shared.handleRequestComplete)(xhr.status, xhr.statusText, xhr.responseText, resolve, reject);
33 }
34 };
35 xhr.send(data);
36 });
37};
38
39var api = {
40 HttpError: _errors.HttpError,
41 HttpParseError: _errors.HttpParseError,
42
43 /**
44 * Factory for the XHR object.
45 * Swap this method out to a fake object for testing.
46 * See: http://sinonjs.org/docs/#server
47 */
48 createXhr: function createXhr() {
49 // NB: Only available when in the browser.
50 return new XMLHttpRequest();
51 },
52
53 /**
54 * Perform a GET operation against the given URL.
55 * @param url: URL of the resource.
56 * @return promise.
57 */
58 get: function get(url) {
59 return send("GET", url);
60 },
61
62 /**
63 * Performs a POST operation against the given URL.
64 *
65 * In REST/Resource-Oriented systems the POST verb
66 * means "create a new resource".
67 *
68 * @param url: URL of the resource.
69 * @param data: The data to send (a primitive value or an object,
70 * will be transformed and sent as JSON).
71 * @return promise.
72 */
73 post: function post(url, data) {
74 return send("POST", url, data);
75 },
76
77 /**
78 * Performs a PUT operation against the given URL.
79 *
80 * In REST/Resource-Oriented systems the PUT verb
81 * means "update a resource".
82 *
83 * @param url: URL of the resource.
84 * @param data: The data to send (a primitive value or an object,
85 * will be transformed and sent as JSON).
86 * @return promise.
87 */
88 put: function put(url, data) {
89 return send("PUT", url, data);
90 },
91
92 /**
93 * Performs a DELETE operation against the given URL.
94 *
95 * In REST/Resource-Oriented systems the DELETE verb
96 * means "remove the resource".
97 *
98 * @param url: URL of the resource.
99 * @return promise.
100 */
101 "delete": function _delete(url) {
102 return send("DELETE", url);
103 }
104};
105
106exports["default"] = api;
107module.exports = exports["default"];
\No newline at end of file