Debian Codegraph @

node/rxjs/src/internal/ajax/ajax.ts

raw
1 import { map } from '../operators/map';
2 import { Observable } from '../Observable';
3 import { AjaxConfig, AjaxRequest, AjaxDirection, ProgressEventType } from './types';
4 import { AjaxResponse } from './AjaxResponse';
5 import { AjaxTimeoutError, AjaxError } from './errors';
6
7 export interface AjaxCreationMethod {
8 /**
9 * Creates an observable that will perform an AJAX request using the
10 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
11 * global scope by default.
12 *
13 * This is the most configurable option, and the basis for all other AJAX calls in the library.
14 *
15 * ## Example
16 *
17 * ```ts
18 * import { ajax } from 'rxjs/ajax';
19 * import { map, catchError, of } from 'rxjs';
20 *
21 * const obs$ = ajax({
22 * method: 'GET',
23 * url: 'https://api.github.com/users?per_page=5',
24 * responseType: 'json'
25 * }).pipe(
26 * map(userResponse => console.log('users: ', userResponse)),
27 * catchError(error => {
28 * console.log('error: ', error);
29 * return of(error);
30 * })
31 * );
32 * ```
33 */
34 <T>(config: AjaxConfig): Observable<AjaxResponse<T>>;
35
36 /**
37 * Perform an HTTP GET using the
38 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
39 * global scope. Defaults to a `responseType` of `"json"`.
40 *
41 * ## Example
42 *
43 * ```ts
44 * import { ajax } from 'rxjs/ajax';
45 * import { map, catchError, of } from 'rxjs';
46 *
47 * const obs$ = ajax('https://api.github.com/users?per_page=5').pipe(
48 * map(userResponse => console.log('users: ', userResponse)),
49 * catchError(error => {
50 * console.log('error: ', error);
51 * return of(error);
52 * })
53 * );
54 * ```
55 */
56 <T>(url: string): Observable<AjaxResponse<T>>;
57
58 /**
59 * Performs an HTTP GET using the
60 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
61 * global scope by default, and a `responseType` of `"json"`.
62 *
63 * @param url The URL to get the resource from
64 * @param headers Optional headers. Case-Insensitive.
65 */
66 get<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
67
68 /**
69 * Performs an HTTP POST using the
70 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
71 * global scope by default, and a `responseType` of `"json"`.
72 *
73 * Before sending the value passed to the `body` argument, it is automatically serialized
74 * based on the specified `responseType`. By default, a JavaScript object will be serialized
75 * to JSON. A `responseType` of `application/x-www-form-urlencoded` will flatten any provided
76 * dictionary object to a url-encoded string.
77 *
78 * @param url The URL to get the resource from
79 * @param body The content to send. The body is automatically serialized.
80 * @param headers Optional headers. Case-Insensitive.
81 */
82 post<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
83
84 /**
85 * Performs an HTTP PUT using the
86 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
87 * global scope by default, and a `responseType` of `"json"`.
88 *
89 * Before sending the value passed to the `body` argument, it is automatically serialized
90 * based on the specified `responseType`. By default, a JavaScript object will be serialized
91 * to JSON. A `responseType` of `application/x-www-form-urlencoded` will flatten any provided
92 * dictionary object to a url-encoded string.
93 *
94 * @param url The URL to get the resource from
95 * @param body The content to send. The body is automatically serialized.
96 * @param headers Optional headers. Case-Insensitive.
97 */
98 put<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
99
100 /**
101 * Performs an HTTP PATCH using the
102 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
103 * global scope by default, and a `responseType` of `"json"`.
104 *
105 * Before sending the value passed to the `body` argument, it is automatically serialized
106 * based on the specified `responseType`. By default, a JavaScript object will be serialized
107 * to JSON. A `responseType` of `application/x-www-form-urlencoded` will flatten any provided
108 * dictionary object to a url-encoded string.
109 *
110 * @param url The URL to get the resource from
111 * @param body The content to send. The body is automatically serialized.
112 * @param headers Optional headers. Case-Insensitive.
113 */
114 patch<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
115
116 /**
117 * Performs an HTTP DELETE using the
118 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
119 * global scope by default, and a `responseType` of `"json"`.
120 *
121 * @param url The URL to get the resource from
122 * @param headers Optional headers. Case-Insensitive.
123 */
124 delete<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>>;
125
126 /**
127 * Performs an HTTP GET using the
128 * [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) in
129 * global scope by default, and returns the hydrated JavaScript object from the
130 * response.
131 *
132 * @param url The URL to get the resource from
133 * @param headers Optional headers. Case-Insensitive.
134 */
135 getJSON<T>(url: string, headers?: Record<string, string>): Observable<T>;
136 }
137
138 function ajaxGet<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
139 return ajax({ method: 'GET', url, headers });
140 }
141
142 function ajaxPost<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
143 return ajax({ method: 'POST', url, body, headers });
144 }
145
146 function ajaxDelete<T>(url: string, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
147 return ajax({ method: 'DELETE', url, headers });
148 }
149
150 function ajaxPut<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
151 return ajax({ method: 'PUT', url, body, headers });
152 }
153
154 function ajaxPatch<T>(url: string, body?: any, headers?: Record<string, string>): Observable<AjaxResponse<T>> {
155 return ajax({ method: 'PATCH', url, body, headers });
156 }
157
158 const mapResponse = map((x: AjaxResponse<any>) => x.response);
159
160 function ajaxGetJSON<T>(url: string, headers?: Record<string, string>): Observable<T> {
161 return mapResponse(
162 ajax<T>({
163 method: 'GET',
164 url,
165 headers,
166 })
167 );
168 }
169
170 /**
171 * There is an ajax operator on the Rx object.
172 *
173 * It creates an observable for an Ajax request with either a request object with
174 * url, headers, etc or a string for a URL.
175 *
176 * ## Examples
177 *
178 * Using `ajax()` to fetch the response object that is being returned from API
179 *
180 * ```ts
181 * import { ajax } from 'rxjs/ajax';
182 * import { map, catchError, of } from 'rxjs';
183 *
184 * const obs$ = ajax('https://api.github.com/users?per_page=5').pipe(
185 * map(userResponse => console.log('users: ', userResponse)),
186 * catchError(error => {
187 * console.log('error: ', error);
188 * return of(error);
189 * })
190 * );
191 *
192 * obs$.subscribe({
193 * next: value => console.log(value),
194 * error: err => console.log(err)
195 * });
196 * ```
197 *
198 * Using `ajax.getJSON()` to fetch data from API
199 *
200 * ```ts
201 * import { ajax } from 'rxjs/ajax';
202 * import { map, catchError, of } from 'rxjs';
203 *
204 * const obs$ = ajax.getJSON('https://api.github.com/users?per_page=5').pipe(
205 * map(userResponse => console.log('users: ', userResponse)),
206 * catchError(error => {
207 * console.log('error: ', error);
208 * return of(error);
209 * })
210 * );
211 *
212 * obs$.subscribe({
213 * next: value => console.log(value),
214 * error: err => console.log(err)
215 * });
216 * ```
217 *
218 * Using `ajax()` with object as argument and method POST with a two seconds delay
219 *
220 * ```ts
221 * import { ajax } from 'rxjs/ajax';
222 * import { map, catchError, of } from 'rxjs';
223 *
224 * const users = ajax({
225 * url: 'https://httpbin.org/delay/2',
226 * method: 'POST',
227 * headers: {
228 * 'Content-Type': 'application/json',
229 * 'rxjs-custom-header': 'Rxjs'
230 * },
231 * body: {
232 * rxjs: 'Hello World!'
233 * }
234 * }).pipe(
235 * map(response => console.log('response: ', response)),
236 * catchError(error => {
237 * console.log('error: ', error);
238 * return of(error);
239 * })
240 * );
241 *
242 * users.subscribe({
243 * next: value => console.log(value),
244 * error: err => console.log(err)
245 * });
246 * ```
247 *
248 * Using `ajax()` to fetch. An error object that is being returned from the request
249 *
250 * ```ts
251 * import { ajax } from 'rxjs/ajax';
252 * import { map, catchError, of } from 'rxjs';
253 *
254 * const obs$ = ajax('https://api.github.com/404').pipe(
255 * map(userResponse => console.log('users: ', userResponse)),
256 * catchError(error => {
257 * console.log('error: ', error);
258 * return of(error);
259 * })
260 * );
261 *
262 * obs$.subscribe({
263 * next: value => console.log(value),
264 * error: err => console.log(err)
265 * });
266 * ```
267 */
268 export const ajax: AjaxCreationMethod = (() => {
269 const create = <T>(urlOrConfig: string | AjaxConfig) => {
270 const config: AjaxConfig =
271 typeof urlOrConfig === 'string'
272 ? {
273 url: urlOrConfig,
274 }
275 : urlOrConfig;
276 return fromAjax<T>(config);
277 };
278
279 create.get = ajaxGet;
280 create.post = ajaxPost;
281 create.delete = ajaxDelete;
282 create.put = ajaxPut;
283 create.patch = ajaxPatch;
284 create.getJSON = ajaxGetJSON;
285
286 return create;
287 })();
288
289 const UPLOAD = 'upload';
290 const DOWNLOAD = 'download';
291 const LOADSTART = 'loadstart';
292 const PROGRESS = 'progress';
293 const LOAD = 'load';
294
295 export function fromAjax<T>(init: AjaxConfig): Observable<AjaxResponse<T>> {
296 return new Observable((destination) => {
297 const config = {
298 // Defaults
299 async: true,
300 crossDomain: false,
301 withCredentials: false,
302 method: 'GET',
303 timeout: 0,
304 responseType: 'json' as XMLHttpRequestResponseType,
305
306 ...init,
307 };
308
309 const { queryParams, body: configuredBody, headers: configuredHeaders } = config;
310
311 let url = config.url;
312 if (!url) {
313 throw new TypeError('url is required');
314 }
315
316 if (queryParams) {
317 let searchParams: URLSearchParams;
318 if (url.includes('?')) {
319 // If the user has passed a URL with a querystring already in it,
320 // we need to combine them. So we're going to split it. There
321 // should only be one `?` in a valid URL.
322 const parts = url.split('?');
323 if (2 < parts.length) {
324 throw new TypeError('invalid url');
325 }
326 // Add the passed queryParams to the params already in the url provided.
327 searchParams = new URLSearchParams(parts[1]);
328 // queryParams is converted to any because the runtime is *much* more permissive than
329 // the types are.
330 new URLSearchParams(queryParams as any).forEach((value, key) => searchParams.set(key, value));
331 // We have to do string concatenation here, because `new URL(url)` does
332 // not like relative URLs like `/this` without a base url, which we can't
333 // specify, nor can we assume `location` will exist, because of node.
334 url = parts[0] + '?' + searchParams;
335 } else {
336 // There is no preexisting querystring, so we can just use URLSearchParams
337 // to convert the passed queryParams into the proper format and encodings.
338 // queryParams is converted to any because the runtime is *much* more permissive than
339 // the types are.
340 searchParams = new URLSearchParams(queryParams as any);
341 url = url + '?' + searchParams;
342 }
343 }
344
345 // Normalize the headers. We're going to make them all lowercase, since
346 // Headers are case insensitive by design. This makes it easier to verify
347 // that we aren't setting or sending duplicates.
348 const headers: Record<string, any> = {};
349 if (configuredHeaders) {
350 for (const key in configuredHeaders) {
351 if (configuredHeaders.hasOwnProperty(key)) {
352 headers[key.toLowerCase()] = configuredHeaders[key];
353 }
354 }
355 }
356
357 const crossDomain = config.crossDomain;
358
359 // Set the x-requested-with header. This is a non-standard header that has
360 // come to be a de facto standard for HTTP requests sent by libraries and frameworks
361 // using XHR. However, we DO NOT want to set this if it is a CORS request. This is
362 // because sometimes this header can cause issues with CORS. To be clear,
363 // None of this is necessary, it's only being set because it's "the thing libraries do"
364 // Starting back as far as JQuery, and continuing with other libraries such as Angular 1,
365 // Axios, et al.
366 if (!crossDomain && !('x-requested-with' in headers)) {
367 headers['x-requested-with'] = 'XMLHttpRequest';
368 }
369
370 // Allow users to provide their XSRF cookie name and the name of a custom header to use to
371 // send the cookie.
372 const { withCredentials, xsrfCookieName, xsrfHeaderName } = config;
373 if ((withCredentials || !crossDomain) && xsrfCookieName && xsrfHeaderName) {
374 const xsrfCookie = document?.cookie.match(new RegExp(`(^|;\\s*)(${xsrfCookieName})=([^;]*)`))?.pop() ?? '';
375 if (xsrfCookie) {
376 headers[xsrfHeaderName] = xsrfCookie;
377 }
378 }
379
380 // Examine the body and determine whether or not to serialize it
381 // and set the content-type in `headers`, if we're able.
382 const body = extractContentTypeAndMaybeSerializeBody(configuredBody, headers);
383
384 // The final request settings.
385 const _request: Readonly<AjaxRequest> = {
386 ...config,
387
388 // Set values we ensured above
389 url,
390 headers,
391 body,
392 };
393
394 let xhr: XMLHttpRequest;
395
396 // Create our XHR so we can get started.
397 xhr = init.createXHR ? init.createXHR() : new XMLHttpRequest();
398
399 {
400 ///////////////////////////////////////////////////
401 // set up the events before open XHR
402 // https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
403 // You need to add the event listeners before calling open() on the request.
404 // Otherwise the progress events will not fire.
405 ///////////////////////////////////////////////////
406
407 const { progressSubscriber, includeDownloadProgress = false, includeUploadProgress = false } = init;
408
409 /**
410 * Wires up an event handler that will emit an error when fired. Used
411 * for timeout and abort events.
412 * @param type The type of event we're treating as an error
413 * @param errorFactory A function that creates the type of error to emit.
414 */
415 const addErrorEvent = (type: string, errorFactory: () => any) => {
416 xhr.addEventListener(type, () => {
417 const error = errorFactory();
418 progressSubscriber?.error?.(error);
419 destination.error(error);
420 });
421 };
422
423 // If the request times out, handle errors appropriately.
424 addErrorEvent('timeout', () => new AjaxTimeoutError(xhr, _request));
425
426 // If the request aborts (due to a network disconnection or the like), handle
427 // it as an error.
428 addErrorEvent('abort', () => new AjaxError('aborted', xhr, _request));
429
430 /**
431 * Creates a response object to emit to the consumer.
432 * @param direction the direction related to the event. Prefixes the event `type` in the
433 * `AjaxResponse` object with "upload_" for events related to uploading and "download_"
434 * for events related to downloading.
435 * @param event the actual event object.
436 */
437 const createResponse = (direction: AjaxDirection, event: ProgressEvent) =>
438 new AjaxResponse<T>(event, xhr, _request, `${direction}_${event.type as ProgressEventType}` as const);
439
440 /**
441 * Wires up an event handler that emits a Response object to the consumer, used for
442 * all events that emit responses, loadstart, progress, and load.
443 * Note that download load handling is a bit different below, because it has
444 * more logic it needs to run.
445 * @param target The target, either the XHR itself or the Upload object.
446 * @param type The type of event to wire up
447 * @param direction The "direction", used to prefix the response object that is
448 * emitted to the consumer. (e.g. "upload_" or "download_")
449 */
450 const addProgressEvent = (target: any, type: string, direction: AjaxDirection) => {
451 target.addEventListener(type, (event: ProgressEvent) => {
452 destination.next(createResponse(direction, event));
453 });
454 };
455
456 if (includeUploadProgress) {
457 [LOADSTART, PROGRESS, LOAD].forEach((type) => addProgressEvent(xhr.upload, type, UPLOAD));
458 }
459
460 if (progressSubscriber) {
461 [LOADSTART, PROGRESS].forEach((type) => xhr.upload.addEventListener(type, (e: any) => progressSubscriber?.next?.(e)));
462 }
463
464 if (includeDownloadProgress) {
465 [LOADSTART, PROGRESS].forEach((type) => addProgressEvent(xhr, type, DOWNLOAD));
466 }
467
468 const emitError = (status?: number) => {
469 const msg = 'ajax error' + (status ? ' ' + status : '');
470 destination.error(new AjaxError(msg, xhr, _request));
471 };
472
473 xhr.addEventListener('error', (e) => {
474 progressSubscriber?.error?.(e);
475 emitError();
476 });
477
478 xhr.addEventListener(LOAD, (event) => {
479 const { status } = xhr;
480 // 4xx and 5xx should error (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
481 if (status < 400) {
482 progressSubscriber?.complete?.();
483
484 let response: AjaxResponse<T>;
485 try {
486 // This can throw in IE, because we end up needing to do a JSON.parse
487 // of the response in some cases to produce object we'd expect from
488 // modern browsers.
489 response = createResponse(DOWNLOAD, event);
490 } catch (err) {
491 destination.error(err);
492 return;
493 }
494
495 destination.next(response);
496 destination.complete();
497 } else {
498 progressSubscriber?.error?.(event);
499 emitError(status);
500 }
501 });
502 }
503
504 const { user, method, async } = _request;
505 // open XHR
506 if (user) {
507 xhr.open(method, url, async, user, _request.password);
508 } else {
509 xhr.open(method, url, async);
510 }
511
512 // timeout, responseType and withCredentials can be set once the XHR is open
513 if (async) {
514 xhr.timeout = _request.timeout;
515 xhr.responseType = _request.responseType;
516 }
517
518 if ('withCredentials' in xhr) {
519 xhr.withCredentials = _request.withCredentials;
520 }
521
522 // set headers
523 for (const key in headers) {
524 if (headers.hasOwnProperty(key)) {
525 xhr.setRequestHeader(key, headers[key]);
526 }
527 }
528
529 // finally send the request
530 if (body) {
531 xhr.send(body);
532 } else {
533 xhr.send();
534 }
535
536 return () => {
537 if (xhr && xhr.readyState !== 4 /*XHR done*/) {
538 xhr.abort();
539 }
540 };
541 });
542 }
543
544 /**
545 * Examines the body to determine if we need to serialize it for them or not.
546 * If the body is a type that XHR handles natively, we just allow it through,
547 * otherwise, if the body is something that *we* can serialize for the user,
548 * we will serialize it, and attempt to set the `content-type` header, if it's
549 * not already set.
550 * @param body The body passed in by the user
551 * @param headers The normalized headers
552 */
553 function extractContentTypeAndMaybeSerializeBody(body: any, headers: Record<string, string>) {
554 if (
555 !body ||
556 typeof body === 'string' ||
557 isFormData(body) ||
558 isURLSearchParams(body) ||
559 isArrayBuffer(body) ||
560 isFile(body) ||
561 isBlob(body) ||
562 isReadableStream(body)
563 ) {
564 // The XHR instance itself can handle serializing these, and set the content-type for us
565 // so we don't need to do that. https://xhr.spec.whatwg.org/#the-send()-method
566 return body;
567 }
568
569 if (isArrayBufferView(body)) {
570 // This is a typed array (e.g. Float32Array or Uint8Array), or a DataView.
571 // XHR can handle this one too: https://fetch.spec.whatwg.org/#concept-bodyinit-extract
572 return body.buffer;
573 }
574
575 if (typeof body === 'object') {
576 // If we have made it here, this is an object, probably a POJO, and we'll try
577 // to serialize it for them. If this doesn't work, it will throw, obviously, which
578 // is okay. The workaround for users would be to manually set the body to their own
579 // serialized string (accounting for circular references or whatever), then set
580 // the content-type manually as well.
581 headers['content-type'] = headers['content-type'] ?? 'application/json;charset=utf-8';
582 return JSON.stringify(body);
583 }
584
585 // If we've gotten past everything above, this is something we don't quite know how to
586 // handle. Throw an error. This will be caught and emitted from the observable.
587 throw new TypeError('Unknown body type');
588 }
589
590 const _toString = Object.prototype.toString;
591
592 function toStringCheck(obj: any, name: string): boolean {
593 return _toString.call(obj) === `[object ${name}]`;
594 }
595
596 function isArrayBuffer(body: any): body is ArrayBuffer {
597 return toStringCheck(body, 'ArrayBuffer');
598 }
599
600 function isFile(body: any): body is File {
601 return toStringCheck(body, 'File');
602 }
603
604 function isBlob(body: any): body is Blob {
605 return toStringCheck(body, 'Blob');
606 }
607
608 function isArrayBufferView(body: any): body is ArrayBufferView {
609 return typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(body);
610 }
611
612 function isFormData(body: any): body is FormData {
613 return typeof FormData !== 'undefined' && body instanceof FormData;
614 }
615
616 function isURLSearchParams(body: any): body is URLSearchParams {
617 return typeof URLSearchParams !== 'undefined' && body instanceof URLSearchParams;
618 }
619
620 function isReadableStream(body: any): body is ReadableStream {
621 return typeof ReadableStream !== 'undefined' && body instanceof ReadableStream;
622 }