1
- /// <reference no-default-lib="true"/>
2
- /// <reference lib="esnext"/>
3
- /// <reference lib="dom" />
4
-
5
1
/** scrapbox.ioが管理しているcache storageから、最新のresponseを取得する
6
2
*
7
3
* ほぼ https://scrapbox.io/daiiz/ScrapboxでのServiceWorkerとCacheの活用#5d2efaffadf4e70000651173 のパクリ
@@ -23,6 +19,29 @@ export const findLatestCache = async (
23
19
}
24
20
} ;
25
21
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
+
26
45
/** prefetchを実行する
27
46
*
28
47
* prefetchしたデータは`"prefetch"`と`"api-yyyy-MM-dd"`に格納される
@@ -33,26 +52,20 @@ export const findLatestCache = async (
33
52
*
34
53
* @param urls prefetchしたいAPIのURLのリスト
35
54
*/
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 ( {
40
57
title : "prefetch" ,
41
58
body : { urls : urls . map ( ( url ) => url . toString ( ) ) } ,
42
59
} ) ;
43
- } ;
44
60
45
61
/** 指定したAPIのcacheの更新を依頼する
46
62
*
47
63
* 更新は10秒ごとに1つずつ実行される
48
64
*
49
65
* @param cacheしたいAPIのURL
50
66
*/
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 } } ) ;
56
69
57
70
const postMessage = < T , U = unknown > (
58
71
data : { title : string ; body : T } ,
0 commit comments