ajax.js 9.9 KB

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