UNPKG

2.28 kBJavaScriptView Raw
1/*
2 * Copyright (c) Microsoft Corporation. All rights reserved.
3 * Licensed under the MIT License.
4 */
5import { NetworkRequestType } from "./utils/Constants";
6/**
7 * XHR client for JSON endpoints
8 * https://www.npmjs.com/package/async-promise
9 * @hidden
10 */
11var XhrClient = /** @class */ (function () {
12 function XhrClient() {
13 }
14 XhrClient.prototype.sendRequestAsync = function (url, method, enableCaching) {
15 var _this = this;
16 return new Promise(function (resolve, reject) {
17 var xhr = new XMLHttpRequest();
18 xhr.open(method, url, /* async: */ true);
19 if (enableCaching) {
20 /*
21 * TODO: (shivb) ensure that this can be cached
22 * xhr.setRequestHeader("Cache-Control", "Public");
23 */
24 }
25 xhr.onload = function () {
26 if (xhr.status < 200 || xhr.status >= 300) {
27 reject(_this.handleError(xhr.responseText));
28 }
29 var jsonResponse;
30 try {
31 jsonResponse = JSON.parse(xhr.responseText);
32 }
33 catch (e) {
34 reject(_this.handleError(xhr.responseText));
35 }
36 var response = {
37 statusCode: xhr.status,
38 body: jsonResponse
39 };
40 resolve(response);
41 };
42 xhr.onerror = function () {
43 reject(xhr.status);
44 };
45 if (method === NetworkRequestType.GET) {
46 xhr.send();
47 }
48 else {
49 throw "not implemented";
50 }
51 });
52 };
53 XhrClient.prototype.handleError = function (responseText) {
54 var jsonResponse;
55 try {
56 jsonResponse = JSON.parse(responseText);
57 if (jsonResponse["error"]) {
58 return jsonResponse["error"];
59 }
60 else {
61 throw responseText;
62 }
63 }
64 catch (e) {
65 return responseText;
66 }
67 };
68 return XhrClient;
69}());
70export { XhrClient };
71//# sourceMappingURL=XHRClient.js.map
\No newline at end of file