Skip to content

Commit 89a2948

Browse files
committed
feat(browser): Save a request and a response into scrapbox.io cache storage
1 parent 86b5684 commit 89a2948

File tree

1 file changed

+27
-14
lines changed

1 file changed

+27
-14
lines changed

browser/dom/cache.ts

+27-14
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,3 @@
1-
/// <reference no-default-lib="true"/>
2-
/// <reference lib="esnext"/>
3-
/// <reference lib="dom" />
4-
51
/** scrapbox.ioが管理しているcache storageから、最新のresponseを取得する
62
*
73
* ほぼ https://scrapbox.io/daiiz/ScrapboxでのServiceWorkerとCacheの活用#5d2efaffadf4e70000651173 のパクリ
@@ -23,6 +19,29 @@ export const findLatestCache = async (
2319
}
2420
};
2521

22+
/** scrapbox.ioが管理しているREST API系のcache storageにresponseを保存する
23+
*
24+
* @param request このrequestに対応するresponseを保存する
25+
* @param response 保存するresponse
26+
*/
27+
export const saveApiCache = async (
28+
request: Request,
29+
response: Response,
30+
): Promise<void> => {
31+
const res = response.clone();
32+
res.headers.set(
33+
"X-Serviceworker-Cached",
34+
`${new Date(res.headers.get("date") ?? new Date()).getTime()}`,
35+
);
36+
const cache = await caches.open(generateCacheName(new Date()));
37+
return await cache.put(request, res);
38+
};
39+
40+
export const generateCacheName = (date: Date): string =>
41+
`api-${date.getFullYear()}-${`${date.getMonth() + 1}`.padStart(2, "0")}-${
42+
`${date.getDate()}`.padStart(2, "0")
43+
}`;
44+
2645
/** prefetchを実行する
2746
*
2847
* prefetchしたデータは`"prefetch"`と`"api-yyyy-MM-dd"`に格納される
@@ -33,26 +52,20 @@ export const findLatestCache = async (
3352
*
3453
* @param urls prefetchしたいAPIのURLのリスト
3554
*/
36-
export const prefetch = async (
37-
urls: (string | URL)[],
38-
): Promise<void> => {
39-
await postMessage({
55+
export const prefetch = (urls: (string | URL)[]): Promise<void> =>
56+
postMessage({
4057
title: "prefetch",
4158
body: { urls: urls.map((url) => url.toString()) },
4259
});
43-
};
4460

4561
/** 指定したAPIのcacheの更新を依頼する
4662
*
4763
* 更新は10秒ごとに1つずつ実行される
4864
*
4965
* @param cacheしたいAPIのURL
5066
*/
51-
export const fetchApiCache = async (
52-
url: string,
53-
): Promise<void> => {
54-
await postMessage({ title: "fetchApiCache", body: { url } });
55-
};
67+
export const fetchApiCache = (url: string): Promise<void> =>
68+
postMessage({ title: "fetchApiCache", body: { url } });
5669

5770
const postMessage = <T, U = unknown>(
5871
data: { title: string; body: T },

0 commit comments

Comments
 (0)