diff --git a/src/PostgrestBuilder.ts b/src/PostgrestBuilder.ts index 621785c9..faa64a0d 100644 --- a/src/PostgrestBuilder.ts +++ b/src/PostgrestBuilder.ts @@ -1,8 +1,6 @@ -// @ts-ignore -import nodeFetch from '@supabase/node-fetch' - import type { Fetch, PostgrestSingleResponse } from './types' import PostgrestError from './PostgrestError' +import { resolveFetch } from './lib/helpers' export default abstract class PostgrestBuilder implements PromiseLike> @@ -27,13 +25,7 @@ export default abstract class PostgrestBuilder this.signal = builder.signal this.isMaybeSingle = builder.isMaybeSingle - if (builder.fetch) { - this.fetch = builder.fetch - } else if (typeof fetch === 'undefined') { - this.fetch = nodeFetch - } else { - this.fetch = fetch - } + this.fetch = resolveFetch(builder.fetch) } /** diff --git a/src/lib/helpers.ts b/src/lib/helpers.ts new file mode 100644 index 00000000..dcecd20b --- /dev/null +++ b/src/lib/helpers.ts @@ -0,0 +1,14 @@ +import { Fetch } from '../types' + +export const resolveFetch = (customFetch?: Fetch): Fetch => { + let _fetch: Fetch + if (customFetch) { + _fetch = customFetch + } else if (typeof fetch === 'undefined') { + _fetch = (...args) => + import('@supabase/node-fetch' as any).then(({ default: fetch }) => fetch(...args)) + } else { + _fetch = fetch + } + return (...args) => _fetch(...args) +} diff --git a/test/helpers.test.ts b/test/helpers.test.ts new file mode 100644 index 00000000..33a838a6 --- /dev/null +++ b/test/helpers.test.ts @@ -0,0 +1,46 @@ +import { resolveFetch } from '../src/lib/helpers' + +describe('resolveFetch', () => { + const TEST_URL = 'https://example.com' + const TEST_OPTIONS = { method: 'GET' } + + beforeEach(() => { + // Reset any mocks between tests + jest.resetModules() + jest.clearAllMocks() + }) + + it('should use custom fetch if provided', async () => { + const customFetch = jest.fn() + const resolvedFetch = resolveFetch(customFetch) + + await resolvedFetch(TEST_URL, TEST_OPTIONS) + + expect(customFetch).toHaveBeenCalledTimes(1) + expect(customFetch).toHaveBeenCalledWith(TEST_URL, TEST_OPTIONS) + }) + + it('should use global fetch if no custom fetch is provided', async () => { + const globalFetch = jest.fn() + global.fetch = globalFetch + const resolvedFetch = resolveFetch() + + await resolvedFetch(TEST_URL, TEST_OPTIONS) + + expect(globalFetch).toHaveBeenCalledTimes(1) + expect(globalFetch).toHaveBeenCalledWith(TEST_URL, TEST_OPTIONS) + }) + + it('should use node-fetch if global fetch is not available', async () => { + const nodeFetch = jest.fn() + jest.mock('@supabase/node-fetch', () => nodeFetch) + + global.fetch = undefined as any + const resolvedFetch = resolveFetch() + + await resolvedFetch(TEST_URL, TEST_OPTIONS) + + expect(nodeFetch).toHaveBeenCalledTimes(1) + expect(nodeFetch).toHaveBeenCalledWith(TEST_URL, TEST_OPTIONS) + }) +})