-
Notifications
You must be signed in to change notification settings - Fork 0
/
_worker.js
57 lines (46 loc) · 1.78 KB
/
_worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
export default {
async fetch(request, env,ctx) {
const url = new URL(request.url);
const api_address = "http://ledg.app/mainnet";
// const { pathname, search } = url;
// const destinationURL = `${api_address}${pathname}${search}`;
if (url.pathname.startsWith('/api')) {
const url = new URL(request.url);
const { pathname, search } = url;
const destinationURL = `${api_address}${pathname}${search}`;
//return new Response(JSON.stringify({destinationURL, data:await fetch(destinationURL)}))
//return new Response(`api: ${destinationURL}`)
async function gatherResponse(response) {
const { headers } = response;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return JSON.stringify(await response.json());
}
return response.text();
}
const init = {
headers: {
"content-type": "application/json;charset=UTF-8",
},
};
//const response = await fetch(destinationURL, init);
//
// const results = await gatherResponse(response);
// const response = new Response(results, init);
const cache=caches.default
const cacheKey=destinationURL
let response=await cache.match(cacheKey);
//let response=undefined
if (!response) {
const fetch_response = await fetch(destinationURL, init);
const results = await gatherResponse(fetch_response);
response = new Response(results,{headers:fetch_response.headers});
response.headers.append("Cache-Control", "s-maxage=60");
ctx.waitUntil(cache.put(cacheKey, response.clone()));
}
return response
}
//return new Response(url)
return env.ASSETS.fetch(request);
},
}