1. /**
  2. * Gracefully handles response headers, providing fallbacks for internal tooling
  3. * and logging errors.
  4. *
  5. * @param {Response} response The HTTP response object.
  6. * @param {object} expectedHeaders An object containing the expected header names and their default values.
  7. * @param {string} toolName The name of the internal tooling.
  8. * @returns {object} An object containing the response headers, with fallbacks applied.
  9. */
  10. function handleResponseHeaders(response, expectedHeaders, toolName) {
  11. const headers = {};
  12. // Iterate through expected headers and apply fallbacks
  13. for (const headerName in expectedHeaders) {
  14. if (expectedHeaders.hasOwnProperty(headerName)) {
  15. const defaultValue = expectedHeaders[headerName];
  16. // Get the header value from the response, or use the default value
  17. headers[headerName] = response.headers.get(headerName) || defaultValue;
  18. }
  19. }
  20. return headers;
  21. }
  22. /**
  23. * Logs an error message to the console.
  24. * @param {string} message The error message.
  25. * @param {string} toolName The name of the internal tooling.
  26. */
  27. function logError(message, toolName) {
  28. console.error(`[${toolName}] Error: ${message}`);
  29. }
  30. // Example usage:
  31. // Assuming you have a response object called 'response'
  32. // and an object 'expectedHeaders' with expected header names and default values.
  33. // const expectedHeaders = {
  34. // 'Content-Type': 'application/json',
  35. // 'X-Custom-Header': 'default_value',
  36. // 'Authorization': 'no_auth' // Example of handling missing auth
  37. // };
  38. // const toolName = 'myInternalTool';
  39. // const processedHeaders = handleResponseHeaders(response, expectedHeaders, toolName);
  40. // console.log(processedHeaders);

Add your comment