All files / src/scripts/instrumentor/patcher/fetch requestInit.ts

100% Statements 10/10
100% Branches 6/6
100% Functions 2/2
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44              16x                               8x       8x 7x 1x   6x 6x     1x     1x     8x    
/**
 * Resolves the HTTP method from a RequestInit object, defaulting to 'GET' if not specified.
 *
 * @param requestInit - Optional RequestInit object that may contain a method property
 * @returns The HTTP method string, defaults to 'GET' if not provided
 */
export function resolveRequestInitMethod(requestInit?: RequestInit) {
  return requestInit?.method ?? 'GET'
}
 
export type FetchParamsWithRequestInit = [any, RequestInit | undefined]
 
/**
 * Sets a header for a fetch request by modifying the RequestInit object in the fetch parameters.
 *
 * If a RequestInit object exists, it updates the headers. If no RequestInit exists, it creates
 * a new one with the specified header.
 *
 * @param name - The header name to set
 * @param value - The header value to set
 * @param fetchParams - Array containing fetch parameters where the second element is RequestInit
 */
export function setHeaderForRequestInit(name: string, value: string, fetchParams: FetchParamsWithRequestInit) {
  const requestInit = fetchParams[1]
 
  let headers: Headers
 
  if (requestInit) {
    if (requestInit.headers instanceof Headers) {
      headers = requestInit.headers
    } else {
      headers = new Headers(requestInit.headers)
      requestInit.headers = headers
    }
  } else {
    headers = new Headers()
 
    // If no requestInit was provided, create it as a second argument
    fetchParams[1] = { headers }
  }
 
  headers.set(name, value)
}