fetch-enhanced
v13.0.2
Published
fetch wrapper with support for automatic HTTP proxy, timeout and accessible agent options
Readme
fetch-enhanced
fetch-enhanced wraps a provided fetch-like function like undici or node-fetch and adds:
- HTTP Proxy discovery from standard environment variables
- HTTP Request Timeout support
- Accessible agent/dispatcher options
Usage
pnpm add fetch-enhanced undiciimport {fetch as undiciFetch} from "undici";
import fetchEnhanced from "fetch-enhanced";
const fetch = fetchEnhanced(undiciFetch, {undici: true});
await fetch("https://example.com");API
fetchEnhanced(fetchImplementation, [opts])
fetchImplementation: Function Afetch-like module that takes(url, opts)and anagent(likenode-fetch) ordispatcher(likeundici) option.optsObjectagentCacheSize: number Size of the agent cache. Default:512.undici: boolean Whether the fetch implementation is undici. Default:false.
Returns: A wrapped fetch function.
fetch(url, [opts])
optsObjecttimeout: number Request timeout in milliseconds. Default: 0 (meaning no timeout).agent/dispatcher: Custom agent fornode-fetchor dispatcher forundici. When specified, proxy discovery andagentOptswill no longer work.agentOpts: object Agent or Dispatcher options. Default:{maxSockets: 64, keepAlive: false}agentOpts.noProxy: boolean Do not use proxy in any case. Default:false.
- Any valid
fetchmodule option, like fornode-fetch
TimeoutError
Error class that can be used for err instanceof TimeoutError:
import {TimeoutError} from "fetch-enhanced";
try {
await fetch("https://example.com", {timeout: 1});
} catch (err) {
console.log(err instanceof TimeoutError);
// => true
}fetch.clearCache()
Clears the agent cache and destroys all cached agents. This is generally only necessary when the proxy environment variables are expected to change during runtime.
process.env.HTTPS_PROXY = "https://proxy1.dev";
await fetch("https://example.com");
fetch.clearCache();
process.env.HTTPS_PROXY = "https://proxy2.dev";
await fetch("https://example.com");© silverwind, distributed under BSD licence
