You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

52 lines
1.2 KiB

8 years ago
  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) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0];
  35. // if-modified-since
  36. if (modifiedSince) {
  37. modifiedSince = new Date(modifiedSince);
  38. lastModified = new Date(lastModified);
  39. notModified = lastModified <= modifiedSince;
  40. }
  41. return !! (etagMatches && notModified);
  42. }