UNPKG

@gam-test/fetch-wrapper

Version:

A simple fetch wrapper for better error handling and less response context

126 lines 3.33 kB
import { DeleteHttpClient } from "./http/DeleteHttpClient.js"; import { GetHttpClient } from "./http/GetHttpClient.js"; import { HeadHttpClient } from "./http/HeadHttpClient.js"; import { PatchHttpClient } from "./http/PatchHttpClient.js"; import { PostHttpClient } from "./http/PostHttpClient.js"; import { PutHttpClient } from "./http/PutHttpClient.js"; class HttpClientManager { #baseUrl; #bodyParser; #config; constructor({ baseUrl, defaultBodyParser, config }) { this.#baseUrl = baseUrl; this.#bodyParser = defaultBodyParser; this.#config = config; } #mergeConfig(config) { if (!config) return { ...this.#config, bodyParser: this.#bodyParser, headers: { ...this.#config?.headers } }; if ("bodyParser" in config) { return { ...this.#config, ...config, bodyParser: config.bodyParser ?? this.#bodyParser, headers: { ...this.#config?.headers, ...config?.headers } }; } return { ...this.#config, ...config, bodyParser: this.#bodyParser, headers: { ...this.#config?.headers, ...config?.headers } }; } #mergeConfigWithData(config) { if (!config) return { ...this.#config, data: null, bodyParser: this.#bodyParser, headers: { ...this.#config?.headers } }; if ("bodyParser" in config) { return { ...this.#config, ...config, bodyParser: config.bodyParser ?? this.#bodyParser, headers: { ...this.#config?.headers, ...config?.headers } }; } return { ...this.#config, ...config, bodyParser: this.#bodyParser, headers: { ...this.#config?.headers, ...config?.headers } }; } async get(url, config) { const client = new GetHttpClient({ url: `${this.#baseUrl}${url}` }); const mergedConfig = this.#mergeConfig(config); return await client.request(mergedConfig); } async head(url, config) { const client = new HeadHttpClient({ url: `${this.#baseUrl}${url}` }); const mergedConfig = this.#mergeConfig(config); return await client.request({ ...mergedConfig, bodyParser: void 0 }); } async post(url, config) { const client = new PostHttpClient({ url: `${this.#baseUrl}${url}` }); const mergedConfig = this.#mergeConfigWithData(config); return await client.request(mergedConfig); } async patch(url, config) { const client = new PatchHttpClient({ url: `${this.#baseUrl}${url}` }); const mergedConfig = this.#mergeConfigWithData(config); return await client.request(mergedConfig); } async put(url, config) { const client = new PutHttpClient({ url: `${this.#baseUrl}${url}` }); const mergedConfig = this.#mergeConfigWithData(config); return await client.request(mergedConfig); } async delete(url, config) { const client = new DeleteHttpClient({ url: `${this.#baseUrl}${url}` }); const mergedConfig = this.#mergeConfigWithData(config); return await client.request(mergedConfig); } } export { HttpClientManager }; //# sourceMappingURL=HttpClientManager.js.map