UNPKG

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