Skip to content

Commit

Permalink
fix: do not crash on fetch(new Request(url)) (#1274)
Browse files Browse the repository at this point in the history
* fix: do not crash on fetch(new Request(url))

* chore: fix headers type
  • Loading branch information
dyladan authored Jul 8, 2020
1 parent 7cce64f commit 264fb36
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
18 changes: 12 additions & 6 deletions packages/opentelemetry-plugin-fetch/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export class FetchPlugin extends core.BasePlugin<Promise<Response>> {
* @param options
* @param spanUrl
*/
private _addHeaders(options: RequestInit, spanUrl: string): void {
private _addHeaders(options: Request | RequestInit, spanUrl: string): void {
if (
!web.shouldPropagateTraceHeaders(
spanUrl,
Expand All @@ -107,9 +107,16 @@ export class FetchPlugin extends core.BasePlugin<Promise<Response>> {
) {
return;
}
const headers: { [key: string]: unknown } = {};
api.propagation.inject(headers);
options.headers = Object.assign({}, headers, options.headers || {});

if (options instanceof Request) {
api.propagation.inject(options.headers, (h, k, v) =>
h.set(k, typeof v === 'string' ? v : String(v))
);
} else {
const headers: Partial<Record<string, unknown>> = {};
api.propagation.inject(headers);
options.headers = Object.assign({}, headers, options.headers || {});
}
}

/**
Expand Down Expand Up @@ -242,8 +249,7 @@ export class FetchPlugin extends core.BasePlugin<Promise<Response>> {
init?: RequestInit
): Promise<Response> {
const url = input instanceof Request ? input.url : input;
const options: RequestInit =
input instanceof Request ? input : init || {};
const options = input instanceof Request ? input : init || {};

const span = plugin._createSpan(url, options);
if (!span) {
Expand Down
8 changes: 7 additions & 1 deletion packages/opentelemetry-plugin-fetch/test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ describe('fetch', () => {
sandbox.stub(core.otperformance, 'timeOrigin').value(0);
sandbox.stub(core.otperformance, 'now').callsFake(() => fakeNow);

function fakeFetch(input: RequestInfo, init: RequestInit = {}) {
function fakeFetch(input: RequestInfo | Request, init: RequestInit = {}) {
return new Promise((resolve, reject) => {
const response: any = {
args: {},
Expand Down Expand Up @@ -459,6 +459,12 @@ describe('fetch', () => {
);
});

it('should set trace headers with a request object', () => {
const r = new Request('url');
window.fetch(r);
assert.ok(typeof r.headers.get(core.X_B3_TRACE_ID) === 'string');
});

it('should NOT clear the resources', () => {
assert.strictEqual(
clearResourceTimingsSpy.args.length,
Expand Down

0 comments on commit 264fb36

Please sign in to comment.