index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. const { NotCachedError } = require('./errors.js')
  2. const CacheEntry = require('./entry.js')
  3. const remote = require('../remote.js')
  4. // do whatever is necessary to get a Response and return it
  5. const cacheFetch = async (request, options) => {
  6. // try to find a cached entry that satisfies this request
  7. const entry = await CacheEntry.find(request, options)
  8. if (!entry) {
  9. // no cached result, if the cache mode is 'only-if-cached' that's a failure
  10. if (options.cache === 'only-if-cached') {
  11. throw new NotCachedError(request.url)
  12. }
  13. // otherwise, we make a request, store it and return it
  14. const response = await remote(request, options)
  15. const newEntry = new CacheEntry({ request, response, options })
  16. return newEntry.store('miss')
  17. }
  18. // we have a cached response that satisfies this request, however if the cache
  19. // mode is 'no-cache' then we send the revalidation request no matter what
  20. if (options.cache === 'no-cache') {
  21. return entry.revalidate(request, options)
  22. }
  23. // if the cached entry is not stale, or if the cache mode is 'force-cache' or
  24. // 'only-if-cached' we can respond with the cached entry. set the status
  25. // based on the result of needsRevalidation and respond
  26. const _needsRevalidation = entry.policy.needsRevalidation(request)
  27. if (options.cache === 'force-cache' ||
  28. options.cache === 'only-if-cached' ||
  29. !_needsRevalidation) {
  30. return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit')
  31. }
  32. // if we got here, the cache entry is stale so revalidate it
  33. return entry.revalidate(request, options)
  34. }
  35. cacheFetch.invalidate = async (request, options) => {
  36. if (!options.cachePath) {
  37. return
  38. }
  39. return CacheEntry.invalidate(request, options)
  40. }
  41. module.exports = cacheFetch