Skip to content

Commit e7e0e56

Browse files
authoredFeb 12, 2024
[proxy-agent] Allow asynchronous getProxyForUrl (#275)
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).
1 parent c854e4c commit e7e0e56

File tree

3 files changed

+35
-2
lines changed

3 files changed

+35
-2
lines changed
 

‎.changeset/nice-pillows-type.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'proxy-agent': minor
3+
---
4+
5+
Allow `getProxyForUrl()` option to return a Promise

‎packages/proxy-agent/src/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ type ValidProtocol = (typeof PROTOCOLS)[number];
2222

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

25-
type GetProxyForUrlCallback = (url: string) => string;
25+
type GetProxyForUrlCallback = (url: string) => string | Promise<string>;
2626

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

120120
if (!proxy) {
121121
debug('Proxy not enabled for URL: %o', url);

‎packages/proxy-agent/test/test.ts

+28
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as fs from 'fs';
22
import * as http from 'http';
33
import * as https from 'https';
44
import { URL } from 'url';
5+
import { promisify } from 'util';
56
import { once } from 'events';
67
import assert from 'assert';
78
import WebSocket, { WebSocketServer } from 'ws';
@@ -287,6 +288,33 @@ describe('ProxyAgent', () => {
287288
assert(gotCall);
288289
assert(requestUrl.href === urlParameter);
289290
});
291+
292+
it('should call provided function with asynchronous getProxyForUrl option', async () => {
293+
let gotCall = false;
294+
let urlParameter = '';
295+
httpsServer.once('request', function (req, res) {
296+
res.end(JSON.stringify(req.headers));
297+
});
298+
299+
const agent = new ProxyAgent({
300+
rejectUnauthorized: false,
301+
getProxyForUrl: async(u) => {
302+
gotCall = true;
303+
urlParameter = u;
304+
await promisify(setTimeout)(1);
305+
return httpsProxyServerUrl.href;
306+
},
307+
});
308+
const requestUrl = new URL('/test', httpsServerUrl);
309+
const res = await req(requestUrl, {
310+
agent,
311+
rejectUnauthorized: false,
312+
});
313+
const body = await json(res);
314+
assert(httpsServerUrl.host === body.host);
315+
assert(gotCall);
316+
assert(requestUrl.href === urlParameter);
317+
});
290318
});
291319

292320
describe('"ws" module', () => {

0 commit comments

Comments
 (0)
Please sign in to comment.