Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

sw.js

108 lines2.8 KB

1// Install event
2self.addEventListener("install", () => {
3 console.log("Service Worker installing");
4 self.skipWaiting();
5});
6​
7// Activate event
8self.addEventListener("activate", (event) => {
9 console.log("Service Worker activating");
10 event.waitUntil(clients.claim());
11});
12​
13// Fetch event - intercept HTTP requests
14self.addEventListener("fetch", (event) => {
15 const { request } = event;
16 const url = new URL(request.url);
17​
18 // Intercept requests to /hello
19 if (url.pathname === "/hello") {
20 event.respondWith(
21 new Response(JSON.stringify({ message: "world" }), {
22 status: 200,
23 headers: { "Content-Type": "application/json" },
24 }),
25 );
26 // } else if (url.pathname === "/api") {
27 // event.respondWith(handleFetch(event));
28 // }
29 } else if (url.pathname.startsWith("/api")) {
30 event.respondWith(handleFetch(event));
31 // event.respondWith(
32 // new Response(
33 // JSON.stringify({
34 // pathname: url.pathname,
35 // 'url.pathname === "/api"': url.pathname === "/api",
36 // }),
37 // {
38 // status: 200,
39 // headers: { "Content-Type": "application/json" },
40 // },
41 // ),
42 // );
43 }
44});
45​
46async function handleFetch(event) {
47 const req = event.request;
48 const url = new URL(req.url);
49​
50 // Read body if method is POST/PUT etc.
51 let requestBody = null;
52 if (req.method !== "GET" && req.method !== "HEAD") {
53 // Clone request to read the body
54 const clone = req.clone();
55 try {
56 requestBody = await clone.json();
57 } catch {
58 requestBody = await clone.text();
59 }
60 }
61​
62 // Create a MessageChannel for response communication
63 const msgChannel = new MessageChannel();
64​
65 // Send message to main thread with one port of MessageChannel
66 const client = await self.clients.get(event.clientId);
67 if (!client) {
68 return fetch(event.request); // fallback to network if no client
69 }
70​
71 client.postMessage(
72 {
73 type: "PROCESS_REQUEST",
74 /*
75 `Request` objects are not directly transferable,
76 so we'll have to reconstruct the requests on the main
77 thread.
78 */
79 body: {
80 requestBody,
81 method: req.method,
82 pathname: url.pathname,
83 },
84 },
85 [msgChannel.port2],
86 );
87​
88 // Promise to wait for response from main thread
89 const responseData = await new Promise((resolve) => {
90 msgChannel.port1.onmessage = (event) => {
91 resolve(event.data.result);
92 };
93 });
94​
95 // TODO: Handle errors
96 if (responseData.contentType === "application/json") {
97 // Respond with the result as JSON
98 return new Response(JSON.stringify(responseData.body), {
99 status: responseData.status,
100 headers: { "Content-Type": "application/json" },
101 });
102 } else {
103 return new Response(responseData.body, {
104 status: responseData.status,
105 headers: { "Content-Type": "text/plain" },
106 });
107 }