From e6450127d1cf5f84f4192ce1dd516d492426cf95 Mon Sep 17 00:00:00 2001 From: Nicole <103509584+nicole0707@users.noreply.github.com> Date: Thu, 5 Oct 2023 23:57:17 +1100 Subject: [PATCH] fix: Agent.Options.factory should accept URL object or string as parameter (#2295) --- test/agent.js | 73 ++++++++++++++++++++++++++++++++++++++++++++++++ types/agent.d.ts | 2 +- 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/test/agent.js b/test/agent.js index ecdbdd2f91d..65afd8b72ac 100644 --- a/test/agent.js +++ b/test/agent.js @@ -10,6 +10,7 @@ const { request, stream, pipeline, + Pool, setGlobalDispatcher, getGlobalDispatcher } = require('../') @@ -267,6 +268,78 @@ test('multiple connections', t => { }) }) +test('agent factory supports URL parameter', (t) => { + t.plan(2) + + const noopHandler = { + onConnect () {}, + onHeaders () {}, + onData () {}, + onComplete () { + server.close() + }, + onError (err) { + throw err + } + } + + const dispatcher = new Agent({ + factory: (origin, opts) => { + t.ok(origin instanceof URL) + return new Pool(origin, opts) + } + }) + + const server = http.createServer((req, res) => { + res.setHeader('Content-Type', 'text/plain') + res.end('asd') + }) + + server.listen(0, () => { + t.doesNotThrow(() => dispatcher.dispatch({ + origin: new URL(`http://localhost:${server.address().port}`), + path: '/', + method: 'GET' + }, noopHandler)) + }) +}) + +test('agent factory supports string parameter', (t) => { + t.plan(2) + + const noopHandler = { + onConnect () {}, + onHeaders () {}, + onData () {}, + onComplete () { + server.close() + }, + onError (err) { + throw err + } + } + + const dispatcher = new Agent({ + factory: (origin, opts) => { + t.ok(typeof origin === 'string') + return new Pool(origin, opts) + } + }) + + const server = http.createServer((req, res) => { + res.setHeader('Content-Type', 'text/plain') + res.end('asd') + }) + + server.listen(0, () => { + t.doesNotThrow(() => dispatcher.dispatch({ + origin: `http://localhost:${server.address().port}`, + path: '/', + method: 'GET' + }, noopHandler)) + }) +}) + test('with globalAgent', t => { t.plan(6) const wanted = 'payload' diff --git a/types/agent.d.ts b/types/agent.d.ts index 08137358058..58081ce9372 100644 --- a/types/agent.d.ts +++ b/types/agent.d.ts @@ -17,7 +17,7 @@ declare class Agent extends Dispatcher{ declare namespace Agent { export interface Options extends Pool.Options { /** Default: `(origin, opts) => new Pool(origin, opts)`. */ - factory?(origin: URL, opts: Object): Dispatcher; + factory?(origin: string | URL, opts: Object): Dispatcher; /** Integer. Default: `0` */ maxRedirections?: number;