Skip to content

Commit bf8b4e8

Browse files
edgraaffbitinn
authored andcommitted
Allow agent option to be a function (#632)
Enable users to return HTTP/HTTPS-specific agent based on request url
1 parent 0c2294e commit bf8b4e8

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -317,7 +317,7 @@ The default values are shown after each option key.
317317
timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.
318318
compress: true, // support gzip/deflate content encoding. false to disable
319319
size: 0, // maximum response body size in bytes. 0 to disable
320-
agent: null // http(s).Agent instance, allows custom proxy, certificate, dns lookup etc.
320+
agent: null // http(s).Agent instance (or function providing one), allows custom proxy, certificate, dns lookup etc.
321321
}
322322
```
323323

src/request.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -230,7 +230,12 @@ export function getNodeRequestOptions(request) {
230230
headers.set('Accept-Encoding', 'gzip,deflate');
231231
}
232232

233-
if (!headers.has('Connection') && !request.agent) {
233+
let agent = request.agent;
234+
if (typeof agent === 'function') {
235+
agent = agent(parsedURL);
236+
}
237+
238+
if (!headers.has('Connection') && !agent) {
234239
headers.set('Connection', 'close');
235240
}
236241

@@ -240,6 +245,6 @@ export function getNodeRequestOptions(request) {
240245
return Object.assign({}, parsedURL, {
241246
method: request.method,
242247
headers: exportNodeCompatibleHeaders(headers),
243-
agent: request.agent
248+
agent
244249
});
245250
}

test/test.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1978,6 +1978,30 @@ describe('node-fetch', () => {
19781978
expect(families[1]).to.equal(family);
19791979
});
19801980
});
1981+
1982+
it('should allow a function supplying the agent', function() {
1983+
const url = `${base}inspect`;
1984+
1985+
const agent = http.Agent({
1986+
keepAlive: true
1987+
});
1988+
1989+
let parsedURL;
1990+
1991+
return fetch(url, {
1992+
agent: function(_parsedURL) {
1993+
parsedURL = _parsedURL;
1994+
return agent;
1995+
}
1996+
}).then(res => {
1997+
return res.json();
1998+
}).then(res => {
1999+
// the agent provider should have been called
2000+
expect(parsedURL.protocol).to.equal('http:');
2001+
// the agent we returned should have been used
2002+
expect(res.headers['connection']).to.equal('keep-alive');
2003+
});
2004+
});
19812005
});
19822006

19832007
describe('Headers', function () {

0 commit comments

Comments
 (0)