Skip to content

Commit

Permalink
Pass req to getProxyForUrl callback (#353)
Browse files Browse the repository at this point in the history
This allows more flexibility in the callback, e.g. for inspecting
request headers before deciding on a given proxy.

---------

Co-authored-by: Anna Henningsen <anna@addaleax.net>
  • Loading branch information
lukekarrys and addaleax authored Dec 6, 2024
1 parent e90e2b2 commit 96b771b
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 4 deletions.
5 changes: 5 additions & 0 deletions .changeset/sixty-carpets-cross.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'proxy-agent': minor
---

Include ClientRequest in getProxyForUrl parameters for additional flexibility
7 changes: 5 additions & 2 deletions packages/proxy-agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ type ValidProtocol =

type AgentConstructor = new (proxy: string, proxyAgentOptions?: ProxyAgentOptions) => Agent;

type GetProxyForUrlCallback = (url: string) => string | Promise<string>;
type GetProxyForUrlCallback = (
url: string,
req: http.ClientRequest
) => string | Promise<string>;

/**
* Shorthands for built-in supported types.
Expand Down Expand Up @@ -128,7 +131,7 @@ export class ProxyAgent extends Agent {
: 'http:';
const host = req.getHeader('host');
const url = new URL(req.path, `${protocol}//${host}`).href;
const proxy = await this.getProxyForUrl(url);
const proxy = await this.getProxyForUrl(url, req);

if (!proxy) {
debug('Proxy not enabled for URL: %o', url);
Expand Down
7 changes: 5 additions & 2 deletions packages/proxy-agent/test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,15 +266,17 @@ describe('ProxyAgent', () => {
it('should call provided function with getProxyForUrl option', async () => {
let gotCall = false;
let urlParameter = '';
let reqParameter: http.ClientRequest | undefined;
httpsServer.once('request', function (req, res) {
res.end(JSON.stringify(req.headers));
});

const agent = new ProxyAgent({
rejectUnauthorized: false,
getProxyForUrl: (u) => {
getProxyForUrl: (u, r) => {
gotCall = true;
urlParameter = u;
reqParameter = r;
return httpsProxyServerUrl.href;
},
});
Expand All @@ -287,6 +289,7 @@ describe('ProxyAgent', () => {
assert(httpsServerUrl.host === body.host);
assert(gotCall);
assert(requestUrl.href === urlParameter);
assert(reqParameter?.constructor.name === 'ClientRequest');
});

it('should call provided function with asynchronous getProxyForUrl option', async () => {
Expand All @@ -298,7 +301,7 @@ describe('ProxyAgent', () => {

const agent = new ProxyAgent({
rejectUnauthorized: false,
getProxyForUrl: async(u) => {
getProxyForUrl: async (u) => {
gotCall = true;
urlParameter = u;
await promisify(setTimeout)(1);
Expand Down

0 comments on commit 96b771b

Please sign in to comment.