日付をcache名として、同じURLのHTTP Responseを複数Cache storageに保存したらどうなるかテスト
Last active
November 16, 2018 11:48
-
-
Save shokai/996f6e65c8117e845d5d5a26b02f3913 to your computer and use it in GitHub Desktop.
日付をcache名として、同じURLのHTTP Responseを複数Cache storageに保存したらどうなるかテスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<title>cache storage multi response</title> | |
<script src="./index.js"></script> | |
</head> | |
<body> | |
open browser console | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const delay = msec => new Promise(resolve => setTimeout(resolve, msec)) | |
window.addEventListener('load', main) | |
const dates = [ '20181116', '20181115', '20181117', ] | |
async function deleteAllCaches () { | |
console.log('deleteAllCaches') | |
for (const key of await caches.keys()) { | |
caches.delete(key) | |
} | |
} | |
async function setHeaders (res, headers) { | |
const newHeaders = new Headers(res.headers) | |
for (const [k, v] of Object.entries(headers)) { | |
newHeaders.set(k, v) | |
} | |
return new Response(await res.blob(), { | |
status: res.status, | |
statusText: res.statusText, | |
headers: newHeaders | |
}) | |
} | |
async function findLatestCache (req) { | |
console.log('findLatestCache', req.url) | |
for (const date of (await caches.keys()).sort().reverse()) { | |
const cache = await caches.open(date) | |
const res = await cache.match(req) | |
if (res) return res | |
} | |
return null | |
} | |
async function main () { | |
console.log('start') | |
await deleteAllCaches() | |
console.log('caches', await caches.keys()) | |
const req = new Request('./index.html') | |
console.log('setup caches', dates) | |
for (const date of dates) { | |
console.log(`setup ${date}`) | |
const cache = await caches.open(date) | |
const res = await fetch(req) | |
cache.put(req, await setHeaders(res, {'x-cached-date': date})) | |
await delay(1000) | |
} | |
console.log('caches', await caches.keys()) | |
console.log('normal caches.match') | |
const res = await caches.match(req) | |
console.log(res) | |
for (const key of res.headers.keys()) { | |
console.log(key, res.headers.get(key)) | |
} | |
console.log('cache.match in order from new date') | |
const res2 = await findLatestCache(req) | |
console.log(res2) | |
for (const key of res2.headers.keys()) { | |
console.log(key, res2.headers.get(key)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment