UNPKG

@twilio/mcs-client

Version:

Twilio Media Content Service client library

157 lines (148 loc) 6.04 kB
/* @license Copyright (c) 2018, Twilio, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ 'use strict'; var global = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; Object.defineProperty(exports, '__esModule', { value: true }); var operationRetrier = require('@twilio/operation-retrier'); var logger = require('../logger.js'); var configuration = require('../configuration.js'); var cancellablePromise = require('../cancellable-promise.js'); const log = logger.Logger.scope("Network"); class Network { constructor(config, transport) { this.config = config; this.transport = transport; } backoffConfig() { return Object.assign(configuration.Configuration.backoffConfigDefault, this.config.backoffConfigOverride); } retryWhenThrottled() { var _a, _b; return ((_b = (_a = this.config.retryWhenThrottledOverride) !== null && _a !== void 0 ? _a : configuration.Configuration.retryWhenThrottledDefault) !== null && _b !== void 0 ? _b : false); } executeWithRetry(request, retryWhenThrottled) { return new cancellablePromise.CancellablePromise(async (resolve, reject, onCancel) => { const retrier = new operationRetrier.Retrier(this.backoffConfig()); const codesToRetryOn = [502, 503, 504]; if (retryWhenThrottled) { codesToRetryOn.push(429); } onCancel(() => { retrier.cancel(); retrier.removeAllListeners(); }); retrier.on("attempt", async () => { try { const requestPromise = request(); onCancel(() => { requestPromise.cancel(); retrier.cancel(); retrier.removeAllListeners(); }); const result = await requestPromise; retrier.succeeded(result); } catch (err) { if (codesToRetryOn.indexOf(err.status) > -1) { retrier.failed(err); } else if (err.message === "Twilsock disconnected") { // Ugly hack. We must make a proper exceptions for twilsock retrier.failed(err); } else { // Fatal error retrier.removeAllListeners(); retrier.cancel(); reject(err); } } }); retrier.on("succeeded", (result) => { resolve(result); }); retrier.on("cancelled", (err) => reject(err)); retrier.on("failed", (err) => reject(err)); retrier.start(); }); } get(url) { return new cancellablePromise.CancellablePromise(async (resolve, reject, onCancel) => { const headers = { "X-Twilio-Token": this.config.token }; const request = this.executeWithRetry(() => this.transport.get(url, headers), this.retryWhenThrottled()); log.trace("sending GET request to ", url, " headers ", headers); onCancel(() => request.cancel()); try { const response = await request; log.trace("response", response); resolve(response); } catch (err) { log.debug(`get() error ${err}`); reject(err); } }); } post(url, category, media, contentType, filename) { const headers = { "X-Twilio-Token": this.config.token, }; if ((typeof FormData === "undefined" || !(media instanceof FormData)) && contentType) { Object.assign(headers, { "Content-Type": contentType, }); } const fullUrl = new URL(url); if (category) { fullUrl.searchParams.append("Category", category); } if (filename) { fullUrl.searchParams.append("Filename", filename); } return new cancellablePromise.CancellablePromise(async (resolve, reject, onCancel) => { const request = this.transport.post(fullUrl.href, headers, media); onCancel(() => request.cancel()); log.trace(`sending POST request to ${url} with headers ${headers}`); let response; try { response = await request; } catch (err) { // If global["XMLHttpRequest"] is undefined, it means that the code is // not being executed in the browser. if (global["XMLHttpRequest"] === undefined && media instanceof FormData) { reject(new TypeError("Posting FormData supported only with browser engine's FormData")); return; } log.debug(`post() error ${err}`); reject(err); return; } log.trace("response", response); resolve(response); }); } } exports.Network = Network; //# sourceMappingURL=network.js.map