source: trip-planner-front/node_modules/rxjs/src/internal/observable/dom/AjaxObservable.ts

Last change on this file was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 16.5 KB
Line 
1import { root } from '../../util/root';
2import { Observable } from '../../Observable';
3import { Subscriber } from '../../Subscriber';
4import { TeardownLogic } from '../../types';
5import { map } from '../../operators/map';
6
7export interface AjaxRequest {
8 url?: string;
9 body?: any;
10 user?: string;
11 async?: boolean;
12 method?: string;
13 headers?: Object;
14 timeout?: number;
15 password?: string;
16 hasContent?: boolean;
17 crossDomain?: boolean;
18 withCredentials?: boolean;
19 createXHR?: () => XMLHttpRequest;
20 progressSubscriber?: Subscriber<any>;
21 responseType?: string;
22}
23
24function getCORSRequest(): XMLHttpRequest {
25 if (root.XMLHttpRequest) {
26 return new root.XMLHttpRequest();
27 } else if (!!root.XDomainRequest) {
28 return new root.XDomainRequest();
29 } else {
30 throw new Error('CORS is not supported by your browser');
31 }
32}
33
34function getXMLHttpRequest(): XMLHttpRequest {
35 if (root.XMLHttpRequest) {
36 return new root.XMLHttpRequest();
37 } else {
38 let progId: string;
39 try {
40 const progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'];
41 for (let i = 0; i < 3; i++) {
42 try {
43 progId = progIds[i];
44 if (new root.ActiveXObject(progId)) {
45 break;
46 }
47 } catch (e) {
48 //suppress exceptions
49 }
50 }
51 return new root.ActiveXObject(progId);
52 } catch (e) {
53 throw new Error('XMLHttpRequest is not supported by your browser');
54 }
55 }
56}
57
58export interface AjaxCreationMethod {
59 (urlOrRequest: string | AjaxRequest): Observable<AjaxResponse>;
60 get(url: string, headers?: Object): Observable<AjaxResponse>;
61 post(url: string, body?: any, headers?: Object): Observable<AjaxResponse>;
62 put(url: string, body?: any, headers?: Object): Observable<AjaxResponse>;
63 patch(url: string, body?: any, headers?: Object): Observable<AjaxResponse>;
64 delete(url: string, headers?: Object): Observable<AjaxResponse>;
65 getJSON<T>(url: string, headers?: Object): Observable<T>;
66}
67
68export function ajaxGet(url: string, headers: Object = null) {
69 return new AjaxObservable<AjaxResponse>({ method: 'GET', url, headers });
70}
71
72export function ajaxPost(url: string, body?: any, headers?: Object): Observable<AjaxResponse> {
73 return new AjaxObservable<AjaxResponse>({ method: 'POST', url, body, headers });
74}
75
76export function ajaxDelete(url: string, headers?: Object): Observable<AjaxResponse> {
77 return new AjaxObservable<AjaxResponse>({ method: 'DELETE', url, headers });
78}
79
80export function ajaxPut(url: string, body?: any, headers?: Object): Observable<AjaxResponse> {
81 return new AjaxObservable<AjaxResponse>({ method: 'PUT', url, body, headers });
82}
83
84export function ajaxPatch(url: string, body?: any, headers?: Object): Observable<AjaxResponse> {
85 return new AjaxObservable<AjaxResponse>({ method: 'PATCH', url, body, headers });
86}
87
88const mapResponse = map((x: AjaxResponse, index: number) => x.response);
89
90export function ajaxGetJSON<T>(url: string, headers?: Object): Observable<T> {
91 return mapResponse(
92 new AjaxObservable<AjaxResponse>({
93 method: 'GET',
94 url,
95 responseType: 'json',
96 headers
97 })
98 );
99}
100
101/**
102 * We need this JSDoc comment for affecting ESDoc.
103 * @extends {Ignored}
104 * @hide true
105 */
106export class AjaxObservable<T> extends Observable<T> {
107 /**
108 * Creates an observable for an Ajax request with either a request object with
109 * url, headers, etc or a string for a URL.
110 *
111 * ## Example
112 * ```ts
113 * import { ajax } from 'rxjs/ajax';
114 *
115 * const source1 = ajax('/products');
116 * const source2 = ajax({ url: 'products', method: 'GET' });
117 * ```
118 *
119 * @param {string|Object} request Can be one of the following:
120 * A string of the URL to make the Ajax call.
121 * An object with the following properties
122 * - url: URL of the request
123 * - body: The body of the request
124 * - method: Method of the request, such as GET, POST, PUT, PATCH, DELETE
125 * - async: Whether the request is async
126 * - headers: Optional headers
127 * - crossDomain: true if a cross domain request, else false
128 * - createXHR: a function to override if you need to use an alternate
129 * XMLHttpRequest implementation.
130 * - resultSelector: a function to use to alter the output value type of
131 * the Observable. Gets {@link AjaxResponse} as an argument.
132 * @return {Observable} An observable sequence containing the XMLHttpRequest.
133 * @static true
134 * @name ajax
135 * @owner Observable
136 * @nocollapse
137 */
138 static create: AjaxCreationMethod = (() => {
139 const create: any = (urlOrRequest: string | AjaxRequest) => {
140 return new AjaxObservable(urlOrRequest);
141 };
142
143 create.get = ajaxGet;
144 create.post = ajaxPost;
145 create.delete = ajaxDelete;
146 create.put = ajaxPut;
147 create.patch = ajaxPatch;
148 create.getJSON = ajaxGetJSON;
149
150 return <AjaxCreationMethod>create;
151 })();
152
153 private request: AjaxRequest;
154
155 constructor(urlOrRequest: string | AjaxRequest) {
156 super();
157
158 const request: AjaxRequest = {
159 async: true,
160 createXHR: function(this: AjaxRequest) {
161 return this.crossDomain ? getCORSRequest() : getXMLHttpRequest();
162 },
163 crossDomain: true,
164 withCredentials: false,
165 headers: {},
166 method: 'GET',
167 responseType: 'json',
168 timeout: 0
169 };
170
171 if (typeof urlOrRequest === 'string') {
172 request.url = urlOrRequest;
173 } else {
174 for (const prop in urlOrRequest) {
175 if (urlOrRequest.hasOwnProperty(prop)) {
176 request[prop] = urlOrRequest[prop];
177 }
178 }
179 }
180
181 this.request = request;
182 }
183
184 /** @deprecated This is an internal implementation detail, do not use. */
185 _subscribe(subscriber: Subscriber<T>): TeardownLogic {
186 return new AjaxSubscriber(subscriber, this.request);
187 }
188}
189
190/**
191 * We need this JSDoc comment for affecting ESDoc.
192 * @ignore
193 * @extends {Ignored}
194 */
195export class AjaxSubscriber<T> extends Subscriber<Event> {
196 private xhr: XMLHttpRequest;
197 private done: boolean = false;
198
199 constructor(destination: Subscriber<T>, public request: AjaxRequest) {
200 super(destination);
201
202 const headers = request.headers = request.headers || {};
203
204 // force CORS if requested
205 if (!request.crossDomain && !this.getHeader(headers, 'X-Requested-With')) {
206 headers['X-Requested-With'] = 'XMLHttpRequest';
207 }
208
209 // ensure content type is set
210 let contentTypeHeader = this.getHeader(headers, 'Content-Type');
211 if (!contentTypeHeader && !(root.FormData && request.body instanceof root.FormData) && typeof request.body !== 'undefined') {
212 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
213 }
214
215 // properly serialize body
216 request.body = this.serializeBody(request.body, this.getHeader(request.headers, 'Content-Type'));
217
218 this.send();
219 }
220
221 next(e: Event): void {
222 this.done = true;
223 const { xhr, request, destination } = this;
224 let result;
225 try {
226 result = new AjaxResponse(e, xhr, request);
227 } catch (err) {
228 return destination.error(err);
229 }
230 destination.next(result);
231 }
232
233 private send(): void {
234 const {
235 request,
236 request: { user, method, url, async, password, headers, body }
237 } = this;
238 try {
239 const xhr = this.xhr = request.createXHR();
240
241 // set up the events before open XHR
242 // https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
243 // You need to add the event listeners before calling open() on the request.
244 // Otherwise the progress events will not fire.
245 this.setupEvents(xhr, request);
246 // open XHR
247 if (user) {
248 xhr.open(method, url, async, user, password);
249 } else {
250 xhr.open(method, url, async);
251 }
252
253 // timeout, responseType and withCredentials can be set once the XHR is open
254 if (async) {
255 xhr.timeout = request.timeout;
256 xhr.responseType = request.responseType as any;
257 }
258
259 if ('withCredentials' in xhr) {
260 xhr.withCredentials = !!request.withCredentials;
261 }
262
263 // set headers
264 this.setHeaders(xhr, headers);
265
266 // finally send the request
267 if (body) {
268 xhr.send(body);
269 } else {
270 xhr.send();
271 }
272 } catch (err) {
273 this.error(err);
274 }
275 }
276
277 private serializeBody(body: any, contentType?: string) {
278 if (!body || typeof body === 'string') {
279 return body;
280 } else if (root.FormData && body instanceof root.FormData) {
281 return body;
282 }
283
284 if (contentType) {
285 const splitIndex = contentType.indexOf(';');
286 if (splitIndex !== -1) {
287 contentType = contentType.substring(0, splitIndex);
288 }
289 }
290
291 switch (contentType) {
292 case 'application/x-www-form-urlencoded':
293 return Object.keys(body).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(body[key])}`).join('&');
294 case 'application/json':
295 return JSON.stringify(body);
296 default:
297 return body;
298 }
299 }
300
301 private setHeaders(xhr: XMLHttpRequest, headers: Object) {
302 for (let key in headers) {
303 if (headers.hasOwnProperty(key)) {
304 xhr.setRequestHeader(key, headers[key]);
305 }
306 }
307 }
308
309 private getHeader(headers: {}, headerName: string): any {
310 for (let key in headers) {
311 if (key.toLowerCase() === headerName.toLowerCase()) {
312 return headers[key];
313 }
314 }
315
316 return undefined;
317 }
318
319 private setupEvents(xhr: XMLHttpRequest, request: AjaxRequest) {
320 const progressSubscriber = request.progressSubscriber;
321
322 function xhrTimeout(this: XMLHttpRequest, e: ProgressEvent): void {
323 const {subscriber, progressSubscriber, request } = (<any>xhrTimeout);
324 if (progressSubscriber) {
325 progressSubscriber.error(e);
326 }
327 let error;
328 try {
329 error = new AjaxTimeoutError(this, request); // TODO: Make betterer.
330 } catch (err) {
331 error = err;
332 }
333 subscriber.error(error);
334 }
335 xhr.ontimeout = xhrTimeout;
336 (<any>xhrTimeout).request = request;
337 (<any>xhrTimeout).subscriber = this;
338 (<any>xhrTimeout).progressSubscriber = progressSubscriber;
339 if (xhr.upload && 'withCredentials' in xhr) {
340 if (progressSubscriber) {
341 let xhrProgress: (e: ProgressEvent) => void;
342 xhrProgress = function(e: ProgressEvent) {
343 const { progressSubscriber } = (<any>xhrProgress);
344 progressSubscriber.next(e);
345 };
346 if (root.XDomainRequest) {
347 xhr.onprogress = xhrProgress;
348 } else {
349 xhr.upload.onprogress = xhrProgress;
350 }
351 (<any>xhrProgress).progressSubscriber = progressSubscriber;
352 }
353 let xhrError: (e: any) => void;
354 xhrError = function(this: XMLHttpRequest, e: ErrorEvent) {
355 const { progressSubscriber, subscriber, request } = (<any>xhrError);
356 if (progressSubscriber) {
357 progressSubscriber.error(e);
358 }
359 let error;
360 try {
361 error = new AjaxError('ajax error', this, request);
362 } catch (err) {
363 error = err;
364 }
365 subscriber.error(error);
366 };
367 xhr.onerror = xhrError;
368 (<any>xhrError).request = request;
369 (<any>xhrError).subscriber = this;
370 (<any>xhrError).progressSubscriber = progressSubscriber;
371 }
372
373 function xhrReadyStateChange(this: XMLHttpRequest, e: Event) {
374 return;
375 }
376 xhr.onreadystatechange = xhrReadyStateChange;
377 (<any>xhrReadyStateChange).subscriber = this;
378 (<any>xhrReadyStateChange).progressSubscriber = progressSubscriber;
379 (<any>xhrReadyStateChange).request = request;
380
381 function xhrLoad(this: XMLHttpRequest, e: Event) {
382 const { subscriber, progressSubscriber, request } = (<any>xhrLoad);
383 if (this.readyState === 4) {
384 // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
385 let status: number = this.status === 1223 ? 204 : this.status;
386 let response: any = (this.responseType === 'text' ? (
387 this.response || this.responseText) : this.response);
388
389 // fix status code when it is 0 (0 status is undocumented).
390 // Occurs when accessing file resources or on Android 4.1 stock browser
391 // while retrieving files from application cache.
392 if (status === 0) {
393 status = response ? 200 : 0;
394 }
395
396 // 4xx and 5xx should error (https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
397 if (status < 400) {
398 if (progressSubscriber) {
399 progressSubscriber.complete();
400 }
401 subscriber.next(e);
402 subscriber.complete();
403 } else {
404 if (progressSubscriber) {
405 progressSubscriber.error(e);
406 }
407 let error;
408 try {
409 error = new AjaxError('ajax error ' + status, this, request);
410 } catch (err) {
411 error = err;
412 }
413 subscriber.error(error);
414 }
415 }
416 }
417 xhr.onload = xhrLoad;
418 (<any>xhrLoad).subscriber = this;
419 (<any>xhrLoad).progressSubscriber = progressSubscriber;
420 (<any>xhrLoad).request = request;
421 }
422
423 unsubscribe() {
424 const { done, xhr } = this;
425 if (!done && xhr && xhr.readyState !== 4 && typeof xhr.abort === 'function') {
426 xhr.abort();
427 }
428 super.unsubscribe();
429 }
430}
431
432/**
433 * A normalized AJAX response.
434 *
435 * @see {@link ajax}
436 *
437 * @class AjaxResponse
438 */
439export class AjaxResponse {
440 /** @type {number} The HTTP status code */
441 status: number;
442
443 /** @type {string|ArrayBuffer|Document|object|any} The response data */
444 response: any;
445
446 /** @type {string} The raw responseText */
447 responseText: string;
448
449 /** @type {string} The responseType (e.g. 'json', 'arraybuffer', or 'xml') */
450 responseType: string;
451
452 constructor(public originalEvent: Event, public xhr: XMLHttpRequest, public request: AjaxRequest) {
453 this.status = xhr.status;
454 this.responseType = xhr.responseType || request.responseType;
455 this.response = parseXhrResponse(this.responseType, xhr);
456 }
457}
458
459export type AjaxErrorNames = 'AjaxError' | 'AjaxTimeoutError';
460
461/**
462 * A normalized AJAX error.
463 *
464 * @see {@link ajax}
465 *
466 * @class AjaxError
467 */
468export interface AjaxError extends Error {
469 /** @type {XMLHttpRequest} The XHR instance associated with the error */
470 xhr: XMLHttpRequest;
471
472 /** @type {AjaxRequest} The AjaxRequest associated with the error */
473 request: AjaxRequest;
474
475 /** @type {number} The HTTP status code */
476 status: number;
477
478 /** @type {string} The responseType (e.g. 'json', 'arraybuffer', or 'xml') */
479 responseType: string;
480
481 /** @type {string|ArrayBuffer|Document|object|any} The response data */
482 response: any;
483}
484
485export interface AjaxErrorCtor {
486 new(message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError;
487}
488
489const AjaxErrorImpl = (() => {
490 function AjaxErrorImpl(this: any, message: string, xhr: XMLHttpRequest, request: AjaxRequest): AjaxError {
491 Error.call(this);
492 this.message = message;
493 this.name = 'AjaxError';
494 this.xhr = xhr;
495 this.request = request;
496 this.status = xhr.status;
497 this.responseType = xhr.responseType || request.responseType;
498 this.response = parseXhrResponse(this.responseType, xhr);
499 return this;
500 }
501 AjaxErrorImpl.prototype = Object.create(Error.prototype);
502 return AjaxErrorImpl;
503})();
504
505export const AjaxError: AjaxErrorCtor = AjaxErrorImpl as any;
506
507function parseJson(xhr: XMLHttpRequest) {
508 // HACK(benlesh): TypeScript shennanigans
509 // tslint:disable-next-line:no-any XMLHttpRequest is defined to always have 'response' inferring xhr as never for the else clause.
510 if ('response' in (xhr as any)) {
511 //IE does not support json as responseType, parse it internally
512 return xhr.responseType ? xhr.response : JSON.parse(xhr.response || xhr.responseText || 'null');
513 } else {
514 return JSON.parse((xhr as any).responseText || 'null');
515 }
516}
517
518function parseXhrResponse(responseType: string, xhr: XMLHttpRequest) {
519 switch (responseType) {
520 case 'json':
521 return parseJson(xhr);
522 case 'xml':
523 return xhr.responseXML;
524 case 'text':
525 default:
526 // HACK(benlesh): TypeScript shennanigans
527 // tslint:disable-next-line:no-any XMLHttpRequest is defined to always have 'response' inferring xhr as never for the else sub-expression.
528 return ('response' in (xhr as any)) ? xhr.response : xhr.responseText;
529 }
530}
531
532export interface AjaxTimeoutError extends AjaxError {
533}
534
535export interface AjaxTimeoutErrorCtor {
536 new(xhr: XMLHttpRequest, request: AjaxRequest): AjaxTimeoutError;
537}
538
539function AjaxTimeoutErrorImpl(this: any, xhr: XMLHttpRequest, request: AjaxRequest) {
540 AjaxError.call(this, 'ajax timeout', xhr, request);
541 this.name = 'AjaxTimeoutError';
542 return this;
543}
544
545/**
546 * @see {@link ajax}
547 *
548 * @class AjaxTimeoutError
549 */
550export const AjaxTimeoutError: AjaxTimeoutErrorCtor = AjaxTimeoutErrorImpl as any;
Note: See TracBrowser for help on using the repository browser.