Skip to content

Commit

Permalink
Allow agent option to be a function (#632)
Browse files Browse the repository at this point in the history
Enable users to return HTTP/HTTPS-specific agent based on request url
  • Loading branch information
edgraaff authored and bitinn committed May 5, 2019
1 parent 0c2294e commit bf8b4e8
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -317,7 +317,7 @@ The default values are shown after each option key.
timeout: 0, // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies). Signal is recommended instead.
compress: true, // support gzip/deflate content encoding. false to disable
size: 0, // maximum response body size in bytes. 0 to disable
agent: null // http(s).Agent instance, allows custom proxy, certificate, dns lookup etc.
agent: null // http(s).Agent instance (or function providing one), allows custom proxy, certificate, dns lookup etc.
}
```

Expand Down
9 changes: 7 additions & 2 deletions src/request.js
Expand Up @@ -230,7 +230,12 @@ export function getNodeRequestOptions(request) {
headers.set('Accept-Encoding', 'gzip,deflate');
}

if (!headers.has('Connection') && !request.agent) {
let agent = request.agent;
if (typeof agent === 'function') {
agent = agent(parsedURL);
}

if (!headers.has('Connection') && !agent) {
headers.set('Connection', 'close');
}

Expand All @@ -240,6 +245,6 @@ export function getNodeRequestOptions(request) {
return Object.assign({}, parsedURL, {
method: request.method,
headers: exportNodeCompatibleHeaders(headers),
agent: request.agent
agent
});
}
24 changes: 24 additions & 0 deletions test/test.js
Expand Up @@ -1978,6 +1978,30 @@ describe('node-fetch', () => {
expect(families[1]).to.equal(family);
});
});

it('should allow a function supplying the agent', function() {
const url = `${base}inspect`;

const agent = http.Agent({
keepAlive: true
});

let parsedURL;

return fetch(url, {
agent: function(_parsedURL) {
parsedURL = _parsedURL;
return agent;
}
}).then(res => {
return res.json();
}).then(res => {
// the agent provider should have been called
expect(parsedURL.protocol).to.equal('http:');
// the agent we returned should have been used
expect(res.headers['connection']).to.equal('keep-alive');
});
});
});

describe('Headers', function () {
Expand Down

0 comments on commit bf8b4e8

Please sign in to comment.