diff --git a/.eslintrc.js b/.eslintrc.js index e38300c2caa9..fdfae1a1a00d 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -134,6 +134,13 @@ module.exports = { "no-console": "error", "no-loss-of-precision": "error", "no-prototype-builtins": 0, + "no-restricted-globals": [ + "error", + { + name: "fetch", + message: "Please use 'fetch' from '@lodestar/api' instead.", + }, + ], "no-restricted-imports": [ "error", { diff --git a/packages/api/src/utils/client/fetch.ts b/packages/api/src/utils/client/fetch.ts index 2cdd98a27af0..a338d82e521f 100644 --- a/packages/api/src/utils/client/fetch.ts +++ b/packages/api/src/utils/client/fetch.ts @@ -5,6 +5,8 @@ */ async function wrappedFetch(url: string | URL, init?: RequestInit): Promise { try { + // This function wraps global `fetch` which should only be directly called here + // eslint-disable-next-line no-restricted-globals return await fetch(url, init); } catch (e) { throw new FetchError(url, e); diff --git a/packages/api/test/unit/client/httpClientFallback.test.ts b/packages/api/test/unit/client/httpClientFallback.test.ts index ff02095b1cc6..e51119741d3c 100644 --- a/packages/api/test/unit/client/httpClientFallback.test.ts +++ b/packages/api/test/unit/client/httpClientFallback.test.ts @@ -1,5 +1,5 @@ import {describe, it, beforeEach, afterEach, expect, vi} from "vitest"; -import {HttpClient} from "../../../src/utils/client/index.js"; +import {HttpClient, fetch} from "../../../src/utils/client/index.js"; describe("httpClient fallback", () => { const testRoute = {url: "/test-route", method: "GET" as const}; @@ -7,7 +7,7 @@ describe("httpClient fallback", () => { // Using fetchSub instead of actually setting up servers because there are some strange // race conditions, where the server stub doesn't count the call in time before the test is over. - const fetchStub = vi.fn(); + const fetchStub = vi.fn, ReturnType>(); let httpClient: HttpClient; @@ -20,7 +20,7 @@ describe("httpClient fallback", () => { const serverErrors = new Map(); // With baseURLs above find the server index associated with that URL - function getServerIndex(url: URL): number { + function getServerIndex(url: URL | string): number { const i = baseUrls.findIndex((baseUrl) => url.toString().startsWith(baseUrl)); if (i < 0) { throw Error(`fetch called with unknown url ${url.toString()}`); @@ -33,7 +33,7 @@ describe("httpClient fallback", () => { httpClient = new HttpClient({ baseUrl: "", urls: baseUrls.map((baseUrl) => ({baseUrl})), - fetch: fetchStub as typeof fetch, + fetch: fetchStub, }); fetchStub.mockImplementation(async (url) => { @@ -57,7 +57,7 @@ describe("httpClient fallback", () => { const callCounts: number[] = []; for (let i = 0; i < serverCount; i++) callCounts[i] = 0; for (const call of fetchStub.mock.calls) { - callCounts[getServerIndex(call)]++; + callCounts[getServerIndex(call[0])]++; } expect(callCounts.join(",")).toBe(expectedCallCounts.join(","));