1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58/** * Expose `fresh()`. */ module.exports = fresh; /** * Check freshness of `req` and `res` headers. * * When the cache is "fresh" __true__ is returned, * otherwise __false__ is returned to indicate that * the cache is now stale. * * @param {Object} req * @param {Object} res * @return {Boolean} * @api public */ function fresh(req, res) { // defaults var etagMatches = true; var notModified = true; // fields var modifiedSince = req['if-modified-since']; var noneMatch = req['if-none-match']; var lastModified = res['last-modified']; var etag = res['etag']; var cc = req['cache-control']; // unconditional request if (!modifiedSince && !noneMatch) return false; // check for no-cache cache request directive if (cc && cc.indexOf('no-cache') !== -1) return false; // parse if-none-match if (noneMatch) noneMatch = noneMatch.split(/ *, */); // if-none-match if (noneMatch) { etagMatches = noneMatch.some(function (match) { return match === '*' || match === etag || match === 'W/' + etag; }); } // if-modified-since if (modifiedSince) { modifiedSince = new Date(modifiedSince); lastModified = new Date(lastModified); notModified = lastModified <= modifiedSince; } return !! (etagMatches && notModified); }