diff --git a/lib/request.js b/lib/request.js index 1fb20c3c..478cebde 100644 --- a/lib/request.js +++ b/lib/request.js @@ -112,6 +112,7 @@ function buildRequest (opts) { function handleUndici (opts, done) { const req = { + origin: baseUrl || opts.url.origin, path: opts.url.pathname + opts.qs, method: opts.method, headers: Object.assign({}, opts.headers), @@ -128,9 +129,7 @@ function buildRequest (opts) { done(new Error('unix socket not supported with undici yet')) return } else { - const options = getUndiciOptions(undiciOpts) - options.dispatcher = undiciAgent - pool = new undici.Pool(baseUrl || opts.url.origin, options) + pool = undiciAgent } // remove forbidden headers diff --git a/test/undici-agent.js b/test/undici-agent.js new file mode 100644 index 00000000..579894b6 --- /dev/null +++ b/test/undici-agent.js @@ -0,0 +1,77 @@ +'use strict' + +const t = require('tap') +const Fastify = require('fastify') +const proxyquire = require('proxyquire') +const http = require('http') +const get = require('simple-get').concat +const undici = require('undici') +const { getUndiciOptions } = require('../lib/request') + +t.plan(10) + +const instance = Fastify() +t.teardown(instance.close.bind(instance)) + +const target = http.createServer((req, res) => { + res.statusCode = 200 + res.end('hello world') +}) + +instance.get('/', (request, reply) => { + reply.from() +}) + +t.teardown(target.close.bind(target)) + +target.listen(0, err => { + t.error(err) + let poolCreation = 0 + + const From = proxyquire('..', { + './lib/request.js': proxyquire('../lib/request.js', { + undici: proxyquire('undici', { + './lib/agent': proxyquire('undici/lib/agent.js', { + './pool': class Pool extends undici.Pool { + constructor (url, options) { + super(url, options) + poolCreation++ + } + } + }) + }) + }) + }) + + instance.register(From, { + base: `http://localhost:${target.address().port}`, + undici: buildUndiciOptions() + }) + + instance.listen(0, err => { + t.error(err) + + get(`http://localhost:${instance.server.address().port}`, (err, res, data) => { + t.error(err) + t.equal(res.statusCode, 200) + t.equal(data.toString(), 'hello world') + t.equal(poolCreation, 1) + + get(`http://localhost:${instance.server.address().port}`, (err, res, data) => { + t.error(err) + t.equal(res.statusCode, 200) + t.equal(data.toString(), 'hello world') + t.equal(poolCreation, 1) + }) + }) + }) +}) + +function buildUndiciOptions () { + return getUndiciOptions({ + connections: 42, + pipelining: 24, + keepAliveTimeout: 4242, + strictContentLength: false + }) +} diff --git a/test/undici-options.js b/test/undici-options.js index 1bd2cd11..6d53806d 100644 --- a/test/undici-options.js +++ b/test/undici-options.js @@ -10,7 +10,7 @@ const { getUndiciOptions } = require('../lib/request') const instance = Fastify() -t.plan(7) +t.plan(6) t.teardown(instance.close.bind(instance)) const target = http.createServer((req, res) => {