UNPKG

2.29 kBJavaScriptView Raw
1"use strict";
2var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4 return new (P || (P = Promise))(function (resolve, reject) {
5 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8 step((generator = generator.apply(thisArg, _arguments || [])).next());
9 });
10};
11Object.defineProperty(exports, "__esModule", { value: true });
12exports.fetchAsync = void 0;
13const isNode = require("detect-node");
14require("isomorphic-fetch");
15// WARNING: This needs to be imported after isomorphic-fetch: https://github.com/mo/abortcontroller-polyfill#using-it-on-browsers-without-fetch
16// tslint:disable-next-line:ordered-imports
17require("abortcontroller-polyfill/dist/abortcontroller-polyfill-only");
18const fetchAsync = (endpoint, options = {}, timeoutMs = 20000) => __awaiter(void 0, void 0, void 0, function* () {
19 if (options.signal || options.timeout) {
20 throw new Error('Cannot call fetchAsync with options.signal or options.timeout. To set a timeout, please use the supplied "timeoutMs" parameter.');
21 }
22 let optionsWithAbortParam;
23 if (!isNode) {
24 const controller = new AbortController();
25 const signal = controller.signal;
26 setTimeout(() => {
27 controller.abort();
28 }, timeoutMs);
29 optionsWithAbortParam = Object.assign({ signal }, options);
30 }
31 else {
32 // HACK: the `timeout` param only exists in `node-fetch`, and not on the `isomorphic-fetch`
33 // `RequestInit` type. Since `isomorphic-fetch` conditionally wraps `node-fetch` when the
34 // execution environment is `Node.js`, we need to cast it to `any` in that scenario.
35 optionsWithAbortParam = Object.assign({ timeout: timeoutMs }, options);
36 }
37 const response = yield fetch(endpoint, optionsWithAbortParam);
38 return response;
39});
40exports.fetchAsync = fetchAsync;
41//# sourceMappingURL=fetch_async.js.map
\No newline at end of file