index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. // otherwise, we make a request, store it and return it
  13. const response = await remote(request, options)
  14. const entry = new CacheEntry({ request, response, options })
  15. return entry.store('miss')
  16. }
  17. // we have a cached response that satisfies this request, however if the cache
  18. // mode is 'no-cache' then we send the revalidation request no matter what
  19. if (options.cache === 'no-cache')
  20. return entry.revalidate(request, options)
  21. // if the cached entry is not stale, or if the cache mode is 'force-cache' or
  22. // 'only-if-cached' we can respond with the cached entry. set the status
  23. // based on the result of needsRevalidation and respond
  24. const _needsRevalidation = entry.policy.needsRevalidation(request)
  25. if (options.cache === 'force-cache' ||
  26. options.cache === 'only-if-cached' ||
  27. !_needsRevalidation)
  28. return entry.respond(request.method, options, _needsRevalidation ? 'stale' : 'hit')
  29. // if we got here, the cache entry is stale so revalidate it
  30. return entry.revalidate(request, options)
  31. }
  32. cacheFetch.invalidate = async (request, options) => {
  33. if (!options.cachePath)
  34. return
  35. return CacheEntry.invalidate(request, options)
  36. }
  37. module.exports = cacheFetch