@voiceflow/fetch
Version:
Voiceflow fetch wrapper and error handling for SDKs
67 lines • 2.51 kB
JavaScript
import { ClientException } from '@voiceflow/exception';
import { HTTPMethod } from './http-method.enum.js';
export 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;
}
config;
fetch;
constructor(fetchOrConfig, config) {
if (typeof fetchOrConfig === 'function') {
this.fetch = fetchOrConfig;
this.config = config ?? {};
}
else {
this.config = fetchOrConfig ?? config ?? {};
}
}
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 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);
}
delete = this.createMethod(HTTPMethod.DELETE);
get = this.createMethod(HTTPMethod.GET);
head = this.createMethod(HTTPMethod.HEAD);
patch = this.createMethod(HTTPMethod.PATCH);
post = this.createMethod(HTTPMethod.POST);
put = this.createMethod(HTTPMethod.PUT);
}
//# sourceMappingURL=fetch.client.js.map