UNPKG

@voiceflow/fetch

Version:

Voiceflow fetch wrapper and error handling for SDKs

70 lines 2.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FetchClient = void 0; const exception_1 = require("@voiceflow/exception"); const http_method_enum_1 = require("./http-method.enum"); class FetchClient { static extractHeaders(headers) { return new Map(headers instanceof Map ? headers : Object.entries(headers ?? {})); } static extractQuery(query) { return new URLSearchParams(query instanceof Map ? Object.entries(query) : query); } static formatURL(baseURL, path, query) { const url = new URL(path, baseURL); query.forEach((value, key) => url.searchParams.append(key, value)); return url.href; } constructor(fetchOrConfig, config) { this.delete = this.createMethod(http_method_enum_1.HTTPMethod.DELETE); this.get = this.createMethod(http_method_enum_1.HTTPMethod.GET); this.head = this.createMethod(http_method_enum_1.HTTPMethod.HEAD); this.patch = this.createMethod(http_method_enum_1.HTTPMethod.PATCH); this.post = this.createMethod(http_method_enum_1.HTTPMethod.POST); this.put = this.createMethod(http_method_enum_1.HTTPMethod.PUT); if (typeof fetchOrConfig === 'function') { this.fetch = fetchOrConfig; this.config = config ?? {}; } else { this.config = fetchOrConfig ?? config ?? {}; } } /* eslint-enable lines-between-class-members */ async send(url, rawOptions) { // eslint-disable-next-line prefer-const let { json, headers, query, body, ...options } = rawOptions; headers = new Map([ ...FetchClient.extractHeaders(this.config.headers).entries(), ...FetchClient.extractHeaders(headers).entries(), ]); query = FetchClient.extractQuery(query); if (json != null) { headers.set('content-type', 'application/json'); body = JSON.stringify(json); } const finalURL = typeof url === 'string' ? FetchClient.formatURL(this.config.baseURL, url, query) : url; const response = await this.raw(finalURL, { ...options, headers: Object.fromEntries(headers.entries()), body, }); if (!response.ok) { throw await new exception_1.ClientException(response).build(); } return response; } createMethod(method) { return (url, options) => { const response = this.send(url, { ...options, method: method.toUpperCase() }); return Object.assign(response, { json: async () => (await response).json(), }); }; } raw(...args) { return (this.fetch ?? window.fetch)(...args); } } exports.FetchClient = FetchClient; //# sourceMappingURL=fetch.client.js.map