1. /**
  2. * Transforms HTTP response data for diagnostics.
  3. *
  4. * @param {Response} response The HTTP response object.
  5. * @returns {object} A transformed object containing relevant response data.
  6. */
  7. function transformResponse(response) {
  8. const transformedData = {
  9. statusCode: response.status, // HTTP status code
  10. headers: Object.entries(response.headers).reduce((acc, [key, value]) => {
  11. acc[key] = value;
  12. return acc;
  13. }, {}), // Headers as an object
  14. responseTime: response.responseTime, // Response time in milliseconds
  15. url: response.url, // The URL of the request
  16. method: response.method, // HTTP Method
  17. body: response.text() || response.json() || response.blob(), // Response body as text, JSON, or Blob
  18. headersSize: response.headers.length, // Number of headers
  19. contentLength: response.headers['Content-Length'] ? parseInt(response.headers['Content-Length']) : 0, // Content length
  20. cacheControl: response.headers['Cache-Control'] || null, // Cache-Control header
  21. contentType: response.headers['Content-Type'] || null, //Content-Type header
  22. };
  23. return transformedData;
  24. }
  25. //Example usage (for testing)
  26. // const mockResponse = {
  27. // status: 200,
  28. // headers: { 'Content-Type': 'application/json', 'X-Custom-Header': 'value' },
  29. // responseTime: 150,
  30. // url: 'https://example.com/api/data',
  31. // method: 'GET',
  32. // text: '{"data": "some data"}',
  33. // };
  34. // const transformed = transformResponse(mockResponse);
  35. // console.log(transformed);

Add your comment