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