From dbfabd2bff113b6cfd17096b12f287472c30c751 Mon Sep 17 00:00:00 2001 From: Philip Szalla Date: Sat, 28 Aug 2021 01:11:30 +0200 Subject: [PATCH] fix(opentelemetry-instrumentation-fetch): fixed override of headers (#2426) * fix(opentelemetry-instrumentation-fetch): fixed override of headers Signed-off-by: Philip Szalla * style(opentelemetry-instrumentation-fetch): removed irritating comment Signed-off-by: Philip Szalla * test(opentelemetry-instrumentation-fetch): added tests for custom headers Signed-off-by: Philip Szalla Co-authored-by: Daniel Dyla --- .../src/fetch.ts | 4 +++ .../test/fetch.test.ts | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/packages/opentelemetry-instrumentation-fetch/src/fetch.ts b/packages/opentelemetry-instrumentation-fetch/src/fetch.ts index d82f6cdc35..01ff72cb2f 100644 --- a/packages/opentelemetry-instrumentation-fetch/src/fetch.ts +++ b/packages/opentelemetry-instrumentation-fetch/src/fetch.ts @@ -158,6 +158,10 @@ export class FetchInstrumentation extends InstrumentationBase< api.propagation.inject(api.context.active(), options.headers, { set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)), }); + } else if(options.headers instanceof Headers) { + api.propagation.inject(api.context.active(), options.headers, { + set: (h, k, v) => h.set(k, typeof v === 'string' ? v : String(v)), + }); } else { const headers: Partial> = {}; api.propagation.inject(api.context.active(), headers); diff --git a/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts b/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts index 1fa0d465c7..1de5b795d0 100644 --- a/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts +++ b/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts @@ -535,6 +535,32 @@ describe('fetch', () => { assert.ok(typeof r.headers.get(X_B3_TRACE_ID) === 'string'); }); + it('should keep custom headers with a request object and a headers object', () => { + const r = new Request('url', { + headers: new Headers({'foo': 'bar'}) + }); + window.fetch(r).catch(() => {}); + assert.ok(r.headers.get('foo') === 'bar'); + }); + + it('should keep custom headers with url, untyped request object and typed headers object', () => { + const url = 'url'; + const init = { + headers: new Headers({'foo': 'bar'}) + }; + window.fetch(url, init).catch(() => {}); + assert.ok(init.headers.get('foo') === 'bar'); + }); + + it('should keep custom headers with url, untyped request object and untyped headers object', () => { + const url = 'url'; + const init = { + headers: {'foo': 'bar'} + }; + window.fetch(url, init).catch(() => {}); + assert.ok(init.headers['foo'] === 'bar'); + }); + it('should pass request object as first parameter to the original function (#2411)', () => { const r = new Request(url); return window.fetch(r).then(() => {