Skip to content

Commit

Permalink
feat(): fetchUtils.ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Eugene Orlovsky committed Sep 12, 2024
1 parent 9161fac commit ae2b62b
Show file tree
Hide file tree
Showing 3 changed files with 211 additions and 232 deletions.
35 changes: 32 additions & 3 deletions src/hooks/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { BaseHttp, ParseHttpRequestOptions, RequestData, UrlAndRequestOptions } from './baseHttp';
import * as logger from '../logger';
import { getEventEntitySize, safeExecuteAsync } from '../utils';
import { convertHeadersToKeyValuePairs } from './fetchUtils';

interface ResponseData {
headers?: Record<string, string>;
Expand Down Expand Up @@ -267,14 +266,14 @@ export class FetchInstrumentation {
} else if (input instanceof Request) {
url = input.url;
options.method = input.method || 'GET';
options.headers = convertHeadersToKeyValuePairs(input.headers);
options.headers = FetchInstrumentation.convertHeadersToKeyValuePairs(input.headers);
}

if (init) {
options.method = init.method || options.method || 'GET';
options.headers = {
...options.headers,
...convertHeadersToKeyValuePairs(init.headers),
...FetchInstrumentation.convertHeadersToKeyValuePairs(init.headers),
};
}

Expand Down Expand Up @@ -333,6 +332,36 @@ export class FetchInstrumentation {
return { url, options };
}

/**
* Converts the headers object to a key-value pair object.
* Fetch library uses multiple format to represent headers, this function will convert them all to a key-value pair object.
* @param {[string, string][] | Record<string, string> | Headers} headers Headers object as used by the fetch library
* @returns {Record<string, string>} The headers as a key-value pair object
* @private
*/
private static convertHeadersToKeyValuePairs(
// @ts-ignore
headers: [string, string][] | Record<string, string> | Headers
): Record<string, string> {
// @ts-ignore
if (headers instanceof Headers) {
const headersObject: Record<string, string> = {};
headers.forEach((value, key) => {
headersObject[key] = value;
});
return headersObject;
}
if (Array.isArray(headers)) {
const headersObject: Record<string, string> = {};
headers.forEach(([key, value]) => {
headersObject[key] = value;
});
return headersObject;
}

return headers;
}

/**
* Adds the headers found in the options object to the fetch arguments, and return the modified arguments.
* The original arguments will not be modified.
Expand Down
Loading

0 comments on commit ae2b62b

Please sign in to comment.