/**
* Caches headers metadata for routine automation with input validation.
* @param {string} url The URL to fetch headers from.
* @param {object} options Optional fetch options.
* @returns {Promise<object>} A promise that resolves to the cached headers metadata or rejects on error.
*/
async function getCachedHeaders(url, options = {}) {
const cacheKey = url; // Use URL as cache key
// Check if headers are already cached
if (typeof cachedHeaders[cacheKey] !== 'undefined') {
console.log(`Retrieving headers from cache for ${url}`);
return cachedHeaders[cacheKey];
}
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const headers = await response.headers.getHeaders();
// Basic input validation - check if headers is an object
if (typeof headers !== 'object' || headers === null) {
throw new Error(`Invalid headers format for ${url}`);
}
cachedHeaders[cacheKey] = headers; // Store headers in cache
console.log(`Cached headers for ${url}`);
return headers;
} catch (error) {
console.error(`Error fetching headers for ${url}:`, error);
throw error; // Re-throw the error to be handled by the caller
}
}
// Initialize the cache
const cachedHeaders = {};
// Example usage (for testing - remove in production)
// async function example() {
// try {
// const headers = await getCachedHeaders('https://example.com');
// console.log(headers);
// } catch (error) {
// console.error(error);
// }
// }
// example();
Add your comment