From ae7d1b1a33dc12354154337128361e7f16643bc7 Mon Sep 17 00:00:00 2001 From: Matthieu Sieben Date: Wed, 6 Mar 2024 17:18:05 +0100 Subject: [PATCH] override request dispatcher from init (#2928) --- lib/web/fetch/request.js | 2 +- test/fetch/issue-2898-comment.js | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 test/fetch/issue-2898-comment.js diff --git a/lib/web/fetch/request.js b/lib/web/fetch/request.js index eb835f543e0..dc9fac83570 100644 --- a/lib/web/fetch/request.js +++ b/lib/web/fetch/request.js @@ -103,7 +103,7 @@ class Request { // 5. Set fallbackMode to "cors". fallbackMode = 'cors' } else { - this[kDispatcher] = input[kDispatcher] + this[kDispatcher] = init.dispatcher || input[kDispatcher] // 6. Otherwise: diff --git a/test/fetch/issue-2898-comment.js b/test/fetch/issue-2898-comment.js new file mode 100644 index 00000000000..c46b80b3ff7 --- /dev/null +++ b/test/fetch/issue-2898-comment.js @@ -0,0 +1,42 @@ +'use strict' + +const { once } = require('node:events') +const { createServer } = require('node:http') +const { test } = require('node:test') +const { Agent, Request, fetch } = require('../..') +const { tspl } = require('@matteo.collina/tspl') + +test('issue #2828, RequestInit dispatcher options overrides Request input dispatcher', async (t) => { + const { strictEqual } = tspl(t, { plan: 2 }) + + class CustomAgentA extends Agent { + dispatch (options, handler) { + options.headers['x-my-header-a'] = 'hello' + return super.dispatch(...arguments) + } + } + + class CustomAgentB extends Agent { + dispatch (options, handler) { + options.headers['x-my-header-b'] = 'world' + return super.dispatch(...arguments) + } + } + + const server = createServer((req, res) => { + strictEqual(req.headers['x-my-header-a'], undefined) + strictEqual(req.headers['x-my-header-b'], 'world') + res.end() + }).listen(0) + + t.after(server.close.bind(server)) + await once(server, 'listening') + + const request = new Request(`http://localhost:${server.address().port}`, { + dispatcher: new CustomAgentA() + }) + + await fetch(request, { + dispatcher: new CustomAgentB() + }) +})