Skip to content

Commit

Permalink
add polyfills for AbortController
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 22, 2023
1 parent 9669913 commit 16da00f
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
8 changes: 6 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export interface CreateFetchOptions {
defaults?: FetchOptions;
fetch?: Fetch;
Headers?: typeof Headers;
AbortController?: typeof AbortController;
}

export type FetchRequest = RequestInfo;
Expand Down Expand Up @@ -88,8 +89,11 @@ const retryStatusCodes = new Set([
]);

export function createFetch(globalOptions: CreateFetchOptions = {}): $Fetch {
const { fetch = globalThis.fetch, Headers = globalThis.Headers } =
globalOptions;
const {
fetch = globalThis.fetch,
Headers = globalThis.Headers,
AbortController = globalThis.AbortController,
} = globalOptions;

async function onError(context: FetchContext): Promise<FetchResponse<any>> {
// Is Abort
Expand Down
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export const fetch =
(() => Promise.reject(new Error("[ofetch] global.fetch is not supported!")));

export const Headers = _globalThis.Headers;
export const AbortController = _globalThis.AbortController;

export const ofetch = createFetch({ fetch, Headers });
export const ofetch = createFetch({ fetch, Headers, AbortController });
export const $fetch = ofetch;
8 changes: 6 additions & 2 deletions src/node.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import http from "node:http";
import https, { AgentOptions } from "node:https";
import nodeFetch, { Headers as _Headers } from "node-fetch-native";
import nodeFetch, {
Headers as _Headers,
AbortController as _AbortController,
} from "node-fetch-native";

import { createFetch } from "./base";

Expand Down Expand Up @@ -33,6 +36,7 @@ export function createNodeFetch() {
export const fetch = globalThis.fetch || createNodeFetch();

export const Headers = globalThis.Headers || _Headers;
export const AbortController = globalThis.AbortController || _AbortController;

export const ofetch = createFetch({ fetch, Headers });
export const ofetch = createFetch({ fetch, Headers, AbortController });
export const $fetch = ofetch;

0 comments on commit 16da00f

Please sign in to comment.