diff --git a/src/config.ts b/src/config.ts index 1beb477..3d9c225 100644 --- a/src/config.ts +++ b/src/config.ts @@ -2,6 +2,8 @@ import type { NearestNode, NodeConfiguration, TsNode } from "@/node"; import { initializeNodes } from "@/node"; +import type { MakeRequestInit } from "@/http/fetch/request"; + interface BaseConfiguration { apiKey: string; randomizeNodes?: boolean; @@ -12,6 +14,10 @@ interface BaseConfiguration { retryIntervalSeconds?: number; sendApiKeyAsQueryParam?: boolean; additionalHeaders?: Record; + fetch?: { + fn?: typeof fetch; + init?: MakeRequestInit; + } } type MakeKeysRequired = T & { diff --git a/src/http/fetch/request.ts b/src/http/fetch/request.ts index 5f12dbb..e474520 100644 --- a/src/http/fetch/request.ts +++ b/src/http/fetch/request.ts @@ -6,16 +6,10 @@ import { constructUrl } from "@/lib/url"; import { sleep } from "@/lib/utils"; import { getNextNode } from "@/node"; -async function makeRequest({ - method, - config, - body, - params, - endpoint, - isImport = false, - currentNodeIndex = 0, - attempt: attemptNum = 1, -}: { + +export type MakeRequestInit = Omit + +async function makeRequest(input: { config: Configuration; method: HttpMethod; body?: TBody; @@ -25,6 +19,17 @@ async function makeRequest({ currentNodeIndex?: number; attempt?: number; }): Promise { + const { + method, + config, + body, + params, + endpoint, + isImport = false, + currentNodeIndex = 0, + attempt: attemptNum = 1, + } = input + const node = getNextNode({ nodes: config.nodes, nearestNode: config.nearestNode, @@ -34,8 +39,10 @@ async function makeRequest({ const url = constructUrl({ baseUrl: node.node.url, params, endpoint }); + const fetchFn = config.fetch?.fn ?? fetch try { - const response = await fetch(url, { + const response = await fetchFn(url, { + ...config.fetch?.init, method, headers: { "Content-Type": isImport ? "text/plain" : "application/json", @@ -67,12 +74,9 @@ async function makeRequest({ await sleep(config.retryIntervalSeconds * 1000); return makeRequest({ - method, - config, - body: isImport ? body : JSON.stringify(body), - params, - currentNodeIndex: node.nextIndex, + ...input, attempt: attemptNum + 1, + currentNodeIndex: node.nextIndex, }); } catch (error) { if (error instanceof RequestError) {