1. /**
  2. * Caches headers metadata for routine automation with input validation.
  3. * @param {string} url The URL to fetch headers from.
  4. * @param {object} options Optional fetch options.
  5. * @returns {Promise<object>} A promise that resolves to the cached headers metadata or rejects on error.
  6. */
  7. async function getCachedHeaders(url, options = {}) {
  8. const cacheKey = url; // Use URL as cache key
  9. // Check if headers are already cached
  10. if (typeof cachedHeaders[cacheKey] !== 'undefined') {
  11. console.log(`Retrieving headers from cache for ${url}`);
  12. return cachedHeaders[cacheKey];
  13. }
  14. try {
  15. const response = await fetch(url, options);
  16. if (!response.ok) {
  17. throw new Error(`HTTP error! Status: ${response.status}`);
  18. }
  19. const headers = await response.headers.getHeaders();
  20. // Basic input validation - check if headers is an object
  21. if (typeof headers !== 'object' || headers === null) {
  22. throw new Error(`Invalid headers format for ${url}`);
  23. }
  24. cachedHeaders[cacheKey] = headers; // Store headers in cache
  25. console.log(`Cached headers for ${url}`);
  26. return headers;
  27. } catch (error) {
  28. console.error(`Error fetching headers for ${url}:`, error);
  29. throw error; // Re-throw the error to be handled by the caller
  30. }
  31. }
  32. // Initialize the cache
  33. const cachedHeaders = {};
  34. // Example usage (for testing - remove in production)
  35. // async function example() {
  36. // try {
  37. // const headers = await getCachedHeaders('https://example.com');
  38. // console.log(headers);
  39. // } catch (error) {
  40. // console.error(error);
  41. // }
  42. // }
  43. // example();

Add your comment