Created
April 11, 2022 02:49
-
-
Save ambar/510843576f1f4e1440eefae49a7fa1e5 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 将 CacheStorage 转换为简单的 key/value 存储 | |
*/ | |
export const createStore = (name: string) => { | |
const cacheP = caches.open(name) | |
const encodeKey = (str: string) => `/?key=${encodeURIComponent(str)}` | |
const decodeKey = (str: string) => str.match(/key=([^;]+)/)?.[1] || '' | |
async function get(key: string) { | |
const cache = await cacheP | |
const r = await cache.match(encodeKey(key)) | |
if (r) { | |
return r.json() | |
} | |
} | |
async function set(key: string, value: unknown) { | |
const cache = await cacheP | |
await cache.put(encodeKey(key), new Response(JSON.stringify(value))) | |
} | |
async function del(key: string) { | |
const cache = await cacheP | |
await cache.delete(encodeKey(key)) | |
} | |
async function keys(): Promise<string[]> { | |
const cache = await cacheP | |
const r = await cache.keys() | |
return r.map(r => decodeKey(r.url)) | |
} | |
async function entries<T>(): Promise<T[]> { | |
const r = await keys() | |
return Promise.all( | |
r.map(async key => [key, await get(key)] as unknown as T) | |
) | |
} | |
return {get, set, del, keys, entries} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment