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.

48 lines
1.1 KiB

  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. // unconditional request
  27. if (!modifiedSince && !noneMatch) return false;
  28. // parse if-none-match
  29. if (noneMatch) noneMatch = noneMatch.split(/ *, */);
  30. // if-none-match
  31. if (noneMatch) etagMatches = ~noneMatch.indexOf(etag) || '*' == noneMatch[0];
  32. // if-modified-since
  33. if (modifiedSince) {
  34. modifiedSince = new Date(modifiedSince);
  35. lastModified = new Date(lastModified);
  36. notModified = lastModified <= modifiedSince;
  37. }
  38. return !! (etagMatches && notModified);
  39. }