/** * Get the expiry time of an XMLHttpRequest response * This function will return a Date object for when the request expires **/ function getCacheExpiry(xhr){ var expiresHeader = xhr.getResponseHeader('Expires'); var cacheControlHeader = xhr.getResponseHeader('Cache-Control'); var expiry = parseCacheControlHeader(cacheControlHeader); if(expiry === undefined) { expiry = parseExpiresHeader(expiresHeader); } expiry = nullifyInvalidExpiration(expiry); return expiry; } /** * Parse the data in the Cache-Control header for information * returns Date object if the Cache-Control header is valid * returns null if there is a valid Cache-Control header that says not to cache * returns undefined if there is no valid Cache-Control header **/ function parseCacheControlHeader(cacheControlHeader){ var headerData = cacheControlHeader.split(","); var expiry = undefined; var keyword; for(var i=0; i -1){ expiry = parseCacheControlAge(keyword, expiry); }else{ expiry = parseCacheControlKeyword(keyword, expiry); } } return expiry; } /** * Parse the max-age value from the Cache-Control header data * returns Date object if the max-age value is valid * returns undefined if there is no valid data **/ function parseCacheControlAge(maxAge, expiry){ if(expiry === null){ return expiry; } var seconds = maxAge.split('=')[1].trim(); seconds = parseInt(seconds); if(seconds === NaN){ return undefined; }else{ var expiryTime = (new Date()).getTime() + seconds * 1000; return (new Date()).setTime(expiryTime); } } /** * Parse non-max-age keywords in the Cache-Control header * returns expiry Date, undefined, or null depending on the keyword behavior **/ function parseCacheControlKeyword(keyword, expiry){ } /** * Parse the data in the Expires header for information * returns Date object if the Expires header is valid * returns null if the Expires header doesn't exist or is malformed **/ function parseExpiresHeader(expiresHeader){ if(expiresHeader === null) { return null; } expires = new Date(expiresHeader); if(expires == "Invalid Date"){ return null; } return expires; } /** * Nullify any invalid expiration Date objects (if they're in the past) **/ function nullifyInvalidExpiration(expiration){ if(expiration instanceof Date && expiration < new Date()){ return null; } return expiration; } module.exports.getCacheExpiry = getCacheExpiry;