Skip to content

feat(browser): Save a request and a response into scrapbox.io cache storage #174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 27 additions & 14 deletions browser/dom/cache.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
/// <reference no-default-lib="true"/>
/// <reference lib="esnext"/>
/// <reference lib="dom" />

/** scrapbox.ioが管理しているcache storageから、最新のresponseを取得する
*
* ほぼ https://scrapbox.io/daiiz/ScrapboxでのServiceWorkerとCacheの活用#5d2efaffadf4e70000651173 のパクリ
Expand All @@ -23,6 +19,29 @@ export const findLatestCache = async (
}
};

/** scrapbox.ioが管理しているREST API系のcache storageにresponseを保存する
*
* @param request このrequestに対応するresponseを保存する
* @param response 保存するresponse
*/
export const saveApiCache = async (
request: Request,
response: Response,
): Promise<void> => {
const res = response.clone();
res.headers.set(
"X-Serviceworker-Cached",
`${new Date(res.headers.get("date") ?? new Date()).getTime()}`,
);
const cache = await caches.open(generateCacheName(new Date()));
return await cache.put(request, res);
};

export const generateCacheName = (date: Date): string =>
`api-${date.getFullYear()}-${`${date.getMonth() + 1}`.padStart(2, "0")}-${
`${date.getDate()}`.padStart(2, "0")
}`;

/** prefetchを実行する
*
* prefetchしたデータは`"prefetch"`と`"api-yyyy-MM-dd"`に格納される
Expand All @@ -33,26 +52,20 @@ export const findLatestCache = async (
*
* @param urls prefetchしたいAPIのURLのリスト
*/
export const prefetch = async (
urls: (string | URL)[],
): Promise<void> => {
await postMessage({
export const prefetch = (urls: (string | URL)[]): Promise<void> =>
postMessage({
title: "prefetch",
body: { urls: urls.map((url) => url.toString()) },
});
};

/** 指定したAPIのcacheの更新を依頼する
*
* 更新は10秒ごとに1つずつ実行される
*
* @param cacheしたいAPIのURL
*/
export const fetchApiCache = async (
url: string,
): Promise<void> => {
await postMessage({ title: "fetchApiCache", body: { url } });
};
export const fetchApiCache = (url: string): Promise<void> =>
postMessage({ title: "fetchApiCache", body: { url } });

const postMessage = <T, U = unknown>(
data: { title: string; body: T },
Expand Down
Loading