UNPKG

4.66 kBJavaScriptView Raw
1'use strict';
2var __assign = (this && this.__assign) || Object.assign || function(t) {
3 for (var s, i = 1, n = arguments.length; i < n; i++) {
4 s = arguments[i];
5 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
6 t[p] = s[p];
7 }
8 return t;
9};
10exports.__esModule = true;
11var GenericResponse = require("http-response-object");
12var Promise = require("promise");
13var ResponsePromise_1 = require("./ResponsePromise");
14exports.ResponsePromise = ResponsePromise_1.ResponsePromise;
15var handle_qs_1 = require("./handle-qs");
16function request(method, url, options) {
17 return ResponsePromise_1["default"](new Promise(function (resolve, reject) {
18 var xhr = new XMLHttpRequest();
19 // check types of arguments
20 if (typeof method !== 'string') {
21 throw new TypeError('The method must be a string.');
22 }
23 if (typeof url !== 'string') {
24 throw new TypeError('The URL/path must be a string.');
25 }
26 if (options == null) {
27 options = {};
28 }
29 if (typeof options !== 'object') {
30 throw new TypeError('Options must be an object (or null).');
31 }
32 method = method.toUpperCase();
33 function attempt(n, options) {
34 request(method, url, {
35 qs: options.qs,
36 headers: options.headers,
37 timeout: options.timeout
38 }).nodeify(function (err, res) {
39 var retry = !!(err || res.statusCode >= 400);
40 if (typeof options.retry === 'function') {
41 retry = options.retry(err, res, n + 1);
42 }
43 if (n >= (options.maxRetries || 5)) {
44 retry = false;
45 }
46 if (retry) {
47 var delay = options.retryDelay;
48 if (typeof options.retryDelay === 'function') {
49 delay = options.retryDelay(err, res, n + 1);
50 }
51 delay = delay || 200;
52 setTimeout(function () {
53 attempt(n + 1, options);
54 }, delay);
55 }
56 else {
57 if (err)
58 reject(err);
59 else
60 resolve(res);
61 }
62 });
63 }
64 if (options.retry && method === 'GET') {
65 return attempt(0, options);
66 }
67 var headers = options.headers || {};
68 // handle cross domain
69 var match;
70 var crossDomain = !!((match = /^([\w-]+:)?\/\/([^\/]+)/.exec(url)) && (match[2] != location.host));
71 if (!crossDomain) {
72 headers = __assign({}, headers, { 'X-Requested-With': 'XMLHttpRequest' });
73 }
74 // handle query string
75 if (options.qs) {
76 url = handle_qs_1["default"](url, options.qs);
77 }
78 // handle json body
79 if (options.json) {
80 options.body = JSON.stringify(options.json);
81 headers = __assign({}, headers, { 'Content-Type': 'application/json' });
82 }
83 if (options.form) {
84 options.body = options.form;
85 }
86 if (options.timeout) {
87 xhr.timeout = options.timeout;
88 var start_1 = Date.now();
89 xhr.ontimeout = function () {
90 var duration = Date.now() - start_1;
91 var err = new Error('Request timed out after ' + duration + 'ms');
92 err.timeout = true;
93 err.duration = duration;
94 reject(err);
95 };
96 }
97 xhr.onreadystatechange = function () {
98 if (xhr.readyState === 4) {
99 var headers = {};
100 xhr.getAllResponseHeaders().split('\r\n').forEach(function (header) {
101 var h = header.split(':');
102 if (h.length > 1) {
103 headers[h[0].toLowerCase()] = h.slice(1).join(':').trim();
104 }
105 });
106 var res = new GenericResponse(xhr.status, headers, xhr.responseText, url);
107 resolve(res);
108 }
109 };
110 // method, url, async
111 xhr.open(method, url, true);
112 for (var name in headers) {
113 xhr.setRequestHeader(name, headers[name]);
114 }
115 // avoid sending empty string (#319)
116 xhr.send(options.body ? options.body : null);
117 }));
118}
119var fd = FormData;
120exports.FormData = fd;
121exports["default"] = request;
122module.exports = request;
123module.exports["default"] = request;
124module.exports.FormData = fd;