source: trip-planner-front/node_modules/make-fetch-happen/lib/cache/index.js@ 76712b2

Last change on this file since 76712b2 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.7 KB
Line 
1const { NotCachedError } = require('./errors.js')
2const CacheEntry = require('./entry.js')
3const remote = require('../remote.js')
4
5// do whatever is necessary to get a Response and return it
6const 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
38cacheFetch.invalidate = async (request, options) => {
39 if (!options.cachePath)
40 return
41
42 return CacheEntry.invalidate(request, options)
43}
44
45module.exports = cacheFetch
Note: See TracBrowser for help on using the repository browser.