Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async function handleInitialFetch(args: {request: Request, key: string}) {
let {request, key} = args
debug && console.log(`fetch(${request.url}): no policy cached; fetching`)
// I explicitly want errors here to propagate. Why? Bundled data will have
// an expired policy stored, so it won't hit this branch. Thus, the only
// requests in here will have nothing to fall back to, so we need some way
// to signal that an error happened.
let response = await fetch(request)
let cachePolicyRequest = requestForCachePolicy(request)
let cachePolicyResponse = responseForCachePolicy(response)
let policy = new CachePolicy(cachePolicyRequest, cachePolicyResponse)
if (policy.storable()) {
debug && console.log(`fetch(${request.url}): caching`)
await cacheItem({key, response, policy})
} else {
debug && console.log(`fetch(${request.url}): not cachable`)
}
return response
}
export async function insertForUrl(url: string, data: mixed) {
let key = `urlcache:${url}`
let {policy: oldPolicy} = await getItem(key)
if (oldPolicy) {
return
}
let req = new Request(url)
let resp = new Response(JSON.stringify(data), {status: 200})
let policy = new CachePolicy(
requestForCachePolicy(req),
responseForCachePolicy(resp),
)
return cacheItem({key, response: resp, policy, bundled: true})
}