index.js 1.3 KB

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