From 88dee75de636df60c08863894b8cb7053fbda101 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Wed, 4 Dec 2024 15:40:03 -0800 Subject: [PATCH] Filter out undefined headers (#40) * Filter out undefined headers Signed-off-by: Matteo Collina * fixup Signed-off-by: Matteo Collina * fixup Signed-off-by: Matteo Collina --------- Signed-off-by: Matteo Collina --- index.js | 10 +++++++++- test/basic.test.js | 20 ++++++++++++++++++++ test/fixtures/empty-headers.js | 11 +++++++++++ 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/empty-headers.js diff --git a/index.js b/index.js index daec2e7..6ff7a3d 100644 --- a/index.js +++ b/index.js @@ -281,10 +281,18 @@ function wire ({ server: newServer, port, ...undiciOpts }) { if (msg.type === 'request') { const { id, opts } = msg + const headers = {} + + for (const [key, value] of Object.entries(opts.headers)) { + if (value !== undefined && value !== null) { + headers[key] = value + } + } + const injectOpts = { method: opts.method, url: opts.path, - headers: opts.headers, + headers, query: opts.query, body: opts.body instanceof Uint8Array ? Buffer.from(opts.body) : opts.body, } diff --git a/test/basic.test.js b/test/basic.test.js index 75d260a..994f637 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -412,3 +412,23 @@ test('aborting a request', async (t) => { signal: abortController.signal, })) }) + +test('empty header', async (t) => { + const worker = new Worker(join(__dirname, 'fixtures', 'empty-headers.js')) + t.after(() => worker.terminate()) + + const interceptor = createThreadInterceptor({ + domain: '.local', + }) + interceptor.route('myserver', worker) + + const agent = new Agent().compose(interceptor) + + const { statusCode, body } = await request('http://myserver.local', { + dispatcher: agent, + headers: { foo: undefined } + }) + + strictEqual(statusCode, 200) + deepStrictEqual(await body.text(), 'hello world') +}) diff --git a/test/fixtures/empty-headers.js b/test/fixtures/empty-headers.js new file mode 100644 index 0000000..a25c9cb --- /dev/null +++ b/test/fixtures/empty-headers.js @@ -0,0 +1,11 @@ +'use strict' + +const { parentPort } = require('node:worker_threads') +const { wire } = require('../../') + +const app = (req, res) => { + // res.setHeader('foo', undefined) + res.end('hello world') +} + +wire({ server: app, port: parentPort })