Skip to content

Commit

Permalink
[proxy-agent] Allow asynchronous getProxyForUrl (#275)
Browse files Browse the repository at this point in the history
This allows users to use an asynchronous getProxyForUrl in case they need
to do asynchronous operations to resolve the correct proxy URL.  This can
be the case, for example, if using Electron.Session.resolveProxy(url).
  • Loading branch information
mook-as committed Feb 12, 2024
1 parent c854e4c commit e7e0e56
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/nice-pillows-type.md
@@ -0,0 +1,5 @@
---
'proxy-agent': minor
---

Allow `getProxyForUrl()` option to return a Promise
4 changes: 2 additions & 2 deletions packages/proxy-agent/src/index.ts
Expand Up @@ -22,7 +22,7 @@ type ValidProtocol = (typeof PROTOCOLS)[number];

type AgentConstructor = new (...args: never[]) => Agent;

type GetProxyForUrlCallback = (url: string) => string;
type GetProxyForUrlCallback = (url: string) => string | Promise<string>;

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

if (!proxy) {
debug('Proxy not enabled for URL: %o', url);
Expand Down
28 changes: 28 additions & 0 deletions packages/proxy-agent/test/test.ts
Expand Up @@ -2,6 +2,7 @@ import * as fs from 'fs';
import * as http from 'http';
import * as https from 'https';
import { URL } from 'url';
import { promisify } from 'util';
import { once } from 'events';
import assert from 'assert';
import WebSocket, { WebSocketServer } from 'ws';
Expand Down Expand Up @@ -287,6 +288,33 @@ describe('ProxyAgent', () => {
assert(gotCall);
assert(requestUrl.href === urlParameter);
});

it('should call provided function with asynchronous getProxyForUrl option', async () => {
let gotCall = false;
let urlParameter = '';
httpsServer.once('request', function (req, res) {
res.end(JSON.stringify(req.headers));
});

const agent = new ProxyAgent({
rejectUnauthorized: false,
getProxyForUrl: async(u) => {
gotCall = true;
urlParameter = u;
await promisify(setTimeout)(1);
return httpsProxyServerUrl.href;
},
});
const requestUrl = new URL('/test', httpsServerUrl);
const res = await req(requestUrl, {
agent,
rejectUnauthorized: false,
});
const body = await json(res);
assert(httpsServerUrl.host === body.host);
assert(gotCall);
assert(requestUrl.href === urlParameter);
});
});

describe('"ws" module', () => {
Expand Down

0 comments on commit e7e0e56

Please sign in to comment.