UNPKG

@pent4gon/fetch

Version:

A modern fetch wrapper with cookie support, written in TypeScript.

74 lines (73 loc) 2.62 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MyFetchError = void 0; const tough_cookie_1 = require("tough-cookie"); const fetch_cookie_1 = __importDefault(require("fetch-cookie")); class MyFetchError extends Error { constructor(status, finalUrl, responseBody) { super(`fetch failed... status: ${status} finalUrl: ${finalUrl} responseBody: ${responseBody} `); this.status = status; this.finalUrl = finalUrl; this.responseBody = responseBody; } } exports.MyFetchError = MyFetchError; class MyFetch { constructor({ cookieJar = new tough_cookie_1.CookieJar(), defaultHeaders = {} } = {}) { this.cookieJar = cookieJar; this.fetchCookie = (0, fetch_cookie_1.default)(fetch, this.cookieJar); this.defaultHeaders = defaultHeaders; } async fetch(url, init) { try { const mergedHeaders = new Headers(this.defaultHeaders); if (init?.headers) { new Headers(init.headers).forEach((value, key) => { mergedHeaders.set(key, value); }); } const response = await this.fetchCookie(url, { ...init, headers: mergedHeaders }); if (!response.ok) { throw new MyFetchError(response.status, response.url, await response.text()); } return response; } catch (e) { if (e instanceof MyFetchError) { throw e; } else { const errorMessage = e instanceof Error ? e.message : String(e); throw new MyFetchError(1000, url.toString(), errorMessage); } } } static create({ cookieJar, defaultHeaders = {} } = {}) { const instance = new MyFetch({ cookieJar, defaultHeaders }); const myFetch = instance.fetch.bind(instance); Object.assign(myFetch, instance); Object.setPrototypeOf(myFetch, MyFetch.prototype); return myFetch; } getCookieJar() { return this.cookieJar.serializeSync(); } setCookieJar(cookieJar) { this.cookieJar = cookieJar; this.fetchCookie = (0, fetch_cookie_1.default)(fetch, this.cookieJar); } getDefaultHeaders() { return this.defaultHeaders; } setDefaultHeaders(defaultHeaders) { this.defaultHeaders = defaultHeaders; } } exports.default = MyFetch;