-
Notifications
You must be signed in to change notification settings - Fork 128
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(node): support http agent with
keepAlive
(#22)
- Loading branch information
Showing
3 changed files
with
34 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,8 +1,32 @@ | ||
import http from 'http' | ||
import https, { AgentOptions } from 'https' | ||
import nodeFetch from 'node-fetch' | ||
|
||
import { createFetch } from './base' | ||
|
||
export * from './base' | ||
|
||
export const fetch = globalThis.fetch || nodeFetch as any as typeof globalThis.fetch | ||
export function createNodeFetch () { | ||
const useKeepAlive = JSON.parse(process.env.FETCH_KEEP_ALIVE || 'false') | ||
if (!useKeepAlive) { | ||
return nodeFetch | ||
} | ||
|
||
// https://github.com/node-fetch/node-fetch#custom-agent | ||
const agentOpts: AgentOptions = { keepAlive: true } | ||
const httpAgent = new http.Agent(agentOpts) | ||
const httpsAgent = new https.Agent(agentOpts) | ||
const nodeFetchOptions = { | ||
agent (parsedURL: any) { | ||
return parsedURL.protocol === 'http:' ? httpAgent : httpsAgent | ||
} | ||
} | ||
|
||
return function nodeFetchWithKeepAlive (input: RequestInfo, init?: RequestInit) { | ||
return (nodeFetch as any)(input, { ...nodeFetchOptions, ...init }) | ||
} | ||
} | ||
|
||
export const fetch = globalThis.fetch || createNodeFetch() | ||
|
||
export const $fetch = createFetch({ fetch }) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,9 @@ | ||
import { fetch as undiciFetch } from 'undici' | ||
import nodeFetch from 'node-fetch' | ||
import { createNodeFetch } from './node' | ||
import { createFetch } from './base' | ||
|
||
export * from './base' | ||
|
||
export const fetch = globalThis.fetch || undiciFetch || nodeFetch | ||
export const fetch = globalThis.fetch || undiciFetch || createNodeFetch() | ||
|
||
export const $fetch = createFetch({ fetch }) |