Skip to content
This repository has been archived by the owner on Jan 22, 2025. It is now read-only.

feat: add fetch option to support cloudflare worker #21388

Closed
wants to merge 1 commit into from
Closed
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
9 changes: 6 additions & 3 deletions web3.js/src/connection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import bs58 from 'bs58';
import {Buffer} from 'buffer';
import fetch from 'cross-fetch';
import type {Response} from 'cross-fetch';
import {
type as pick,
Expand Down Expand Up @@ -751,6 +750,7 @@ export type PerfSample = {
function createRpcClient(
url: string,
useHttps: boolean,
_fetch: typeof fetch,
httpHeaders?: HttpHeaders,
fetchMiddleware?: FetchMiddleware,
disableRetryOnRateLimit?: boolean,
Expand All @@ -767,7 +767,7 @@ function createRpcClient(
return new Promise<Response>((resolve, reject) => {
fetchMiddleware(url, options, async (url: string, options: any) => {
try {
resolve(await fetch(url, options));
resolve(await _fetch(url, options));
} catch (error) {
reject(error);
}
Expand Down Expand Up @@ -798,7 +798,7 @@ function createRpcClient(
if (fetchWithMiddleware) {
res = await fetchWithMiddleware(url, options);
} else {
res = await fetch(url, options);
res = await _fetch(url, options);
}

if (res.status !== 429 /* Too many requests */) {
Expand Down Expand Up @@ -2067,10 +2067,12 @@ export class Connection {
*
* @param endpoint URL to the fullnode JSON RPC endpoint
* @param commitmentOrConfig optional default commitment level or optional ConnectionConfig configuration object
* @param fetch optional fetch compatible [API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) for making a request
*/
constructor(
endpoint: string,
commitmentOrConfig?: Commitment | ConnectionConfig,
_fetch?: typeof fetch,
) {
let url = new URL(endpoint);
const useHttps = url.protocol === 'https:';
Expand All @@ -2097,6 +2099,7 @@ export class Connection {
this._rpcClient = createRpcClient(
url.toString(),
useHttps,
_fetch || require('cross-fetch'),
httpHeaders,
fetchMiddleware,
disableRetryOnRateLimit,
Expand Down
15 changes: 15 additions & 0 deletions web3.js/test/connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3338,5 +3338,20 @@ describe('Connection', () => {
const version = await connection.getVersion();
expect(version['solana-core']).to.be.ok;
});

it('custom fetch option', async () => {
let count = 0;
const connection = new Connection(
'https://api.mainnet-beta.solana.com',
{},
(input, init) => {
count++;
return fetch(input, init);
},
);
const version = await connection.getVersion();
expect(version['solana-core']).to.be.ok;
expect(count).to.eq(1);
});
}
});