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

Commit

Permalink
feat: add fetch option to support cloudflare worker
Browse files Browse the repository at this point in the history
  • Loading branch information
ZhengYuTay authored and mergify-bot committed Nov 24, 2021
1 parent 238d65c commit e0c2d8b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
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);
});
}
});

0 comments on commit e0c2d8b

Please sign in to comment.