Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion lib/dispatcher/dispatcher.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict'
const EventEmitter = require('node:events')
const { kUrl } = require('../core/symbols')

class Dispatcher extends EventEmitter {
dispatch () {
Expand Down Expand Up @@ -36,7 +37,19 @@ class Dispatcher extends EventEmitter {
}

return new Proxy(this, {
get: (target, key) => key === 'dispatch' ? dispatch : target[key]
get: (target, key) => {
if (key !== 'dispatch') {
return target[key]
}

return function composedDispatch (opts, handler) {
const origin = target[kUrl]?.origin
if (origin != null && opts?.origin == null) {
opts = { ...opts, origin }
}
return dispatch(opts, handler)
}
}
})
}
}
Expand Down
35 changes: 34 additions & 1 deletion test/interceptors/dns.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const { once } = require('node:events')
const { tspl } = require('@matteo.collina/tspl')
const pem = require('@metcoder95/https-pem')

const { interceptors, Agent, request } = require('../..')
const { interceptors, Agent, Client, request } = require('../..')
const { dns } = interceptors

// Helper to check if IPv6 is available for localhost
Expand Down Expand Up @@ -480,6 +480,39 @@ test('Should throw when on dual-stack disabled (6)', { skip: !ipv6Available }, a
await t.completed
})

test('Should resolve client origin when request origin is omitted', async t => {
t = tspl(t, { plan: 3 })

const server = createServer({ joinDuplicateHeaders: true }, (req, res) => {
res.writeHead(200, { 'content-type': 'text/plain' })
res.end('hello world!')
})

server.listen(0)
await once(server, 'listening')

const client = new Client(`http://localhost:${server.address().port}`).compose(dns({
lookup: (origin, _opts, cb) => {
t.equal(origin.hostname, 'localhost')
cb(null, [{ address: '127.0.0.1', family: 4 }])
}
}))

after(async () => {
await client.close()
server.close()
await once(server, 'close')
})

const response = await client.request({
method: 'GET',
path: '/'
})

t.equal(response.statusCode, 200)
t.equal(await response.body.text(), 'hello world!')
})

test('Should automatically resolve IPs (dual stack disabled - 4)', async t => {
t = tspl(t, { plan: 6 })

Expand Down