Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -12,6 +14,10 @@ interface BaseConfiguration {
retryIntervalSeconds?: number;
sendApiKeyAsQueryParam?: boolean;
additionalHeaders?: Record<string, string>;
fetch?: {
fn?: typeof fetch;
init?: MakeRequestInit;
}
}

type MakeKeysRequired<T, K extends keyof T> = T & {
Expand Down
36 changes: 20 additions & 16 deletions src/http/fetch/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,10 @@ import { constructUrl } from "@/lib/url";
import { sleep } from "@/lib/utils";
import { getNextNode } from "@/node";

async function makeRequest<TBody, TReturn>({
method,
config,
body,
params,
endpoint,
isImport = false,
currentNodeIndex = 0,
attempt: attemptNum = 1,
}: {

export type MakeRequestInit = Omit<RequestInit, 'method' | 'body' | 'headers'>

async function makeRequest<TBody, TReturn>(input: {
config: Configuration;
method: HttpMethod;
body?: TBody;
Expand All @@ -25,6 +19,17 @@ async function makeRequest<TBody, TReturn>({
currentNodeIndex?: number;
attempt?: number;
}): Promise<TReturn> {
const {
method,
config,
body,
params,
endpoint,
isImport = false,
currentNodeIndex = 0,
attempt: attemptNum = 1,
} = input

const node = getNextNode({
nodes: config.nodes,
nearestNode: config.nearestNode,
Expand All @@ -34,8 +39,10 @@ async function makeRequest<TBody, TReturn>({

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",
Expand Down Expand Up @@ -67,12 +74,9 @@ async function makeRequest<TBody, TReturn>({
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) {
Expand Down