Skip to content

Commit a14d2d0

Browse files
committed
Fetch function configuration
1 parent 9a9ed64 commit a14d2d0

File tree

2 files changed

+26
-16
lines changed

2 files changed

+26
-16
lines changed

src/config.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import type { NearestNode, NodeConfiguration, TsNode } from "@/node";
22

33
import { initializeNodes } from "@/node";
44

5+
import type { MakeRequestInit } from "@/http/fetch/request";
6+
57
interface BaseConfiguration {
68
apiKey: string;
79
randomizeNodes?: boolean;
@@ -12,6 +14,10 @@ interface BaseConfiguration {
1214
retryIntervalSeconds?: number;
1315
sendApiKeyAsQueryParam?: boolean;
1416
additionalHeaders?: Record<string, string>;
17+
fetch?: {
18+
fn?: typeof fetch;
19+
init?: MakeRequestInit;
20+
}
1521
}
1622

1723
type MakeKeysRequired<T, K extends keyof T> = T & {

src/http/fetch/request.ts

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,10 @@ import { constructUrl } from "@/lib/url";
66
import { sleep } from "@/lib/utils";
77
import { getNextNode } from "@/node";
88

9-
async function makeRequest<TBody, TReturn>({
10-
method,
11-
config,
12-
body,
13-
params,
14-
endpoint,
15-
isImport = false,
16-
currentNodeIndex = 0,
17-
attempt: attemptNum = 1,
18-
}: {
9+
10+
export type MakeRequestInit = Omit<RequestInit, 'method' | 'body' | 'headers'>
11+
12+
async function makeRequest<TBody, TReturn>(input: {
1913
config: Configuration;
2014
method: HttpMethod;
2115
body?: TBody;
@@ -25,6 +19,17 @@ async function makeRequest<TBody, TReturn>({
2519
currentNodeIndex?: number;
2620
attempt?: number;
2721
}): Promise<TReturn> {
22+
const {
23+
method,
24+
config,
25+
body,
26+
params,
27+
endpoint,
28+
isImport = false,
29+
currentNodeIndex = 0,
30+
attempt: attemptNum = 1,
31+
} = input
32+
2833
const node = getNextNode({
2934
nodes: config.nodes,
3035
nearestNode: config.nearestNode,
@@ -34,8 +39,10 @@ async function makeRequest<TBody, TReturn>({
3439

3540
const url = constructUrl({ baseUrl: node.node.url, params, endpoint });
3641

42+
const fetchFn = config.fetch?.fn ?? fetch
3743
try {
38-
const response = await fetch(url, {
44+
const response = await fetchFn(url, {
45+
...config.fetch?.init,
3946
method,
4047
headers: {
4148
"Content-Type": isImport ? "text/plain" : "application/json",
@@ -67,12 +74,9 @@ async function makeRequest<TBody, TReturn>({
6774
await sleep(config.retryIntervalSeconds * 1000);
6875

6976
return makeRequest({
70-
method,
71-
config,
72-
body: isImport ? body : JSON.stringify(body),
73-
params,
74-
currentNodeIndex: node.nextIndex,
77+
...input,
7578
attempt: attemptNum + 1,
79+
currentNodeIndex: node.nextIndex,
7680
});
7781
} catch (error) {
7882
if (error instanceof RequestError) {

0 commit comments

Comments
 (0)