ajax.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. "use strict";
  2. var __assign = (this && this.__assign) || function () {
  3. __assign = Object.assign || function(t) {
  4. for (var s, i = 1, n = arguments.length; i < n; i++) {
  5. s = arguments[i];
  6. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  7. t[p] = s[p];
  8. }
  9. return t;
  10. };
  11. return __assign.apply(this, arguments);
  12. };
  13. Object.defineProperty(exports, "__esModule", { value: true });
  14. exports.fromAjax = exports.ajax = void 0;
  15. var map_1 = require("../operators/map");
  16. var Observable_1 = require("../Observable");
  17. var AjaxResponse_1 = require("./AjaxResponse");
  18. var errors_1 = require("./errors");
  19. function ajaxGet(url, headers) {
  20. return exports.ajax({ method: 'GET', url: url, headers: headers });
  21. }
  22. function ajaxPost(url, body, headers) {
  23. return exports.ajax({ method: 'POST', url: url, body: body, headers: headers });
  24. }
  25. function ajaxDelete(url, headers) {
  26. return exports.ajax({ method: 'DELETE', url: url, headers: headers });
  27. }
  28. function ajaxPut(url, body, headers) {
  29. return exports.ajax({ method: 'PUT', url: url, body: body, headers: headers });
  30. }
  31. function ajaxPatch(url, body, headers) {
  32. return exports.ajax({ method: 'PATCH', url: url, body: body, headers: headers });
  33. }
  34. var mapResponse = map_1.map(function (x) { return x.response; });
  35. function ajaxGetJSON(url, headers) {
  36. return mapResponse(exports.ajax({
  37. method: 'GET',
  38. url: url,
  39. headers: headers,
  40. }));
  41. }
  42. exports.ajax = (function () {
  43. var create = function (urlOrConfig) {
  44. var config = typeof urlOrConfig === 'string'
  45. ? {
  46. url: urlOrConfig,
  47. }
  48. : urlOrConfig;
  49. return fromAjax(config);
  50. };
  51. create.get = ajaxGet;
  52. create.post = ajaxPost;
  53. create.delete = ajaxDelete;
  54. create.put = ajaxPut;
  55. create.patch = ajaxPatch;
  56. create.getJSON = ajaxGetJSON;
  57. return create;
  58. })();
  59. var UPLOAD = 'upload';
  60. var DOWNLOAD = 'download';
  61. var LOADSTART = 'loadstart';
  62. var PROGRESS = 'progress';
  63. var LOAD = 'load';
  64. function fromAjax(init) {
  65. return new Observable_1.Observable(function (destination) {
  66. var _a, _b;
  67. var config = __assign({ async: true, crossDomain: false, withCredentials: false, method: 'GET', timeout: 0, responseType: 'json' }, init);
  68. var queryParams = config.queryParams, configuredBody = config.body, configuredHeaders = config.headers;
  69. var url = config.url;
  70. if (!url) {
  71. throw new TypeError('url is required');
  72. }
  73. if (queryParams) {
  74. var searchParams_1;
  75. if (url.includes('?')) {
  76. var parts = url.split('?');
  77. if (2 < parts.length) {
  78. throw new TypeError('invalid url');
  79. }
  80. searchParams_1 = new URLSearchParams(parts[1]);
  81. new URLSearchParams(queryParams).forEach(function (value, key) { return searchParams_1.set(key, value); });
  82. url = parts[0] + '?' + searchParams_1;
  83. }
  84. else {
  85. searchParams_1 = new URLSearchParams(queryParams);
  86. url = url + '?' + searchParams_1;
  87. }
  88. }
  89. var headers = {};
  90. if (configuredHeaders) {
  91. for (var key in configuredHeaders) {
  92. if (configuredHeaders.hasOwnProperty(key)) {
  93. headers[key.toLowerCase()] = configuredHeaders[key];
  94. }
  95. }
  96. }
  97. var crossDomain = config.crossDomain;
  98. if (!crossDomain && !('x-requested-with' in headers)) {
  99. headers['x-requested-with'] = 'XMLHttpRequest';
  100. }
  101. var withCredentials = config.withCredentials, xsrfCookieName = config.xsrfCookieName, xsrfHeaderName = config.xsrfHeaderName;
  102. if ((withCredentials || !crossDomain) && xsrfCookieName && xsrfHeaderName) {
  103. var xsrfCookie = (_b = (_a = document === null || document === void 0 ? void 0 : document.cookie.match(new RegExp("(^|;\\s*)(" + xsrfCookieName + ")=([^;]*)"))) === null || _a === void 0 ? void 0 : _a.pop()) !== null && _b !== void 0 ? _b : '';
  104. if (xsrfCookie) {
  105. headers[xsrfHeaderName] = xsrfCookie;
  106. }
  107. }
  108. var body = extractContentTypeAndMaybeSerializeBody(configuredBody, headers);
  109. var _request = __assign(__assign({}, config), { url: url,
  110. headers: headers,
  111. body: body });
  112. var xhr;
  113. xhr = init.createXHR ? init.createXHR() : new XMLHttpRequest();
  114. {
  115. var progressSubscriber_1 = init.progressSubscriber, _c = init.includeDownloadProgress, includeDownloadProgress = _c === void 0 ? false : _c, _d = init.includeUploadProgress, includeUploadProgress = _d === void 0 ? false : _d;
  116. var addErrorEvent = function (type, errorFactory) {
  117. xhr.addEventListener(type, function () {
  118. var _a;
  119. var error = errorFactory();
  120. (_a = progressSubscriber_1 === null || progressSubscriber_1 === void 0 ? void 0 : progressSubscriber_1.error) === null || _a === void 0 ? void 0 : _a.call(progressSubscriber_1, error);
  121. destination.error(error);
  122. });
  123. };
  124. addErrorEvent('timeout', function () { return new errors_1.AjaxTimeoutError(xhr, _request); });
  125. addErrorEvent('abort', function () { return new errors_1.AjaxError('aborted', xhr, _request); });
  126. var createResponse_1 = function (direction, event) {
  127. return new AjaxResponse_1.AjaxResponse(event, xhr, _request, direction + "_" + event.type);
  128. };
  129. var addProgressEvent_1 = function (target, type, direction) {
  130. target.addEventListener(type, function (event) {
  131. destination.next(createResponse_1(direction, event));
  132. });
  133. };
  134. if (includeUploadProgress) {
  135. [LOADSTART, PROGRESS, LOAD].forEach(function (type) { return addProgressEvent_1(xhr.upload, type, UPLOAD); });
  136. }
  137. if (progressSubscriber_1) {
  138. [LOADSTART, PROGRESS].forEach(function (type) { return xhr.upload.addEventListener(type, function (e) { var _a; return (_a = progressSubscriber_1 === null || progressSubscriber_1 === void 0 ? void 0 : progressSubscriber_1.next) === null || _a === void 0 ? void 0 : _a.call(progressSubscriber_1, e); }); });
  139. }
  140. if (includeDownloadProgress) {
  141. [LOADSTART, PROGRESS].forEach(function (type) { return addProgressEvent_1(xhr, type, DOWNLOAD); });
  142. }
  143. var emitError_1 = function (status) {
  144. var msg = 'ajax error' + (status ? ' ' + status : '');
  145. destination.error(new errors_1.AjaxError(msg, xhr, _request));
  146. };
  147. xhr.addEventListener('error', function (e) {
  148. var _a;
  149. (_a = progressSubscriber_1 === null || progressSubscriber_1 === void 0 ? void 0 : progressSubscriber_1.error) === null || _a === void 0 ? void 0 : _a.call(progressSubscriber_1, e);
  150. emitError_1();
  151. });
  152. xhr.addEventListener(LOAD, function (event) {
  153. var _a, _b;
  154. var status = xhr.status;
  155. if (status < 400) {
  156. (_a = progressSubscriber_1 === null || progressSubscriber_1 === void 0 ? void 0 : progressSubscriber_1.complete) === null || _a === void 0 ? void 0 : _a.call(progressSubscriber_1);
  157. var response = void 0;
  158. try {
  159. response = createResponse_1(DOWNLOAD, event);
  160. }
  161. catch (err) {
  162. destination.error(err);
  163. return;
  164. }
  165. destination.next(response);
  166. destination.complete();
  167. }
  168. else {
  169. (_b = progressSubscriber_1 === null || progressSubscriber_1 === void 0 ? void 0 : progressSubscriber_1.error) === null || _b === void 0 ? void 0 : _b.call(progressSubscriber_1, event);
  170. emitError_1(status);
  171. }
  172. });
  173. }
  174. var user = _request.user, method = _request.method, async = _request.async;
  175. if (user) {
  176. xhr.open(method, url, async, user, _request.password);
  177. }
  178. else {
  179. xhr.open(method, url, async);
  180. }
  181. if (async) {
  182. xhr.timeout = _request.timeout;
  183. xhr.responseType = _request.responseType;
  184. }
  185. if ('withCredentials' in xhr) {
  186. xhr.withCredentials = _request.withCredentials;
  187. }
  188. for (var key in headers) {
  189. if (headers.hasOwnProperty(key)) {
  190. xhr.setRequestHeader(key, headers[key]);
  191. }
  192. }
  193. if (body) {
  194. xhr.send(body);
  195. }
  196. else {
  197. xhr.send();
  198. }
  199. return function () {
  200. if (xhr && xhr.readyState !== 4) {
  201. xhr.abort();
  202. }
  203. };
  204. });
  205. }
  206. exports.fromAjax = fromAjax;
  207. function extractContentTypeAndMaybeSerializeBody(body, headers) {
  208. var _a;
  209. if (!body ||
  210. typeof body === 'string' ||
  211. isFormData(body) ||
  212. isURLSearchParams(body) ||
  213. isArrayBuffer(body) ||
  214. isFile(body) ||
  215. isBlob(body) ||
  216. isReadableStream(body)) {
  217. return body;
  218. }
  219. if (isArrayBufferView(body)) {
  220. return body.buffer;
  221. }
  222. if (typeof body === 'object') {
  223. headers['content-type'] = (_a = headers['content-type']) !== null && _a !== void 0 ? _a : 'application/json;charset=utf-8';
  224. return JSON.stringify(body);
  225. }
  226. throw new TypeError('Unknown body type');
  227. }
  228. var _toString = Object.prototype.toString;
  229. function toStringCheck(obj, name) {
  230. return _toString.call(obj) === "[object " + name + "]";
  231. }
  232. function isArrayBuffer(body) {
  233. return toStringCheck(body, 'ArrayBuffer');
  234. }
  235. function isFile(body) {
  236. return toStringCheck(body, 'File');
  237. }
  238. function isBlob(body) {
  239. return toStringCheck(body, 'Blob');
  240. }
  241. function isArrayBufferView(body) {
  242. return typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(body);
  243. }
  244. function isFormData(body) {
  245. return typeof FormData !== 'undefined' && body instanceof FormData;
  246. }
  247. function isURLSearchParams(body) {
  248. return typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams;
  249. }
  250. function isReadableStream(body) {
  251. return typeof ReadableStream !== 'undefined' && body instanceof ReadableStream;
  252. }
  253. //# sourceMappingURL=ajax.js.map