Files
bknd/examples/sw/sw.ts
2024-11-27 17:15:22 +01:00

36 lines
793 B
TypeScript

// To support types
// https://github.com/microsoft/TypeScript/issues/14877
declare const self: ServiceWorkerGlobalScope;
import { App } from "bknd";
async function getBknd() {
const bknd = App.create({
connection: {
type: "libsql",
config: {
url: "http://localhost:8080"
}
}
});
await bknd.build();
return bknd;
}
self.addEventListener("fetch", async (e) => {
// only intercept api requests
if (e.request.url.includes("/api/")) {
e.respondWith(
(async () => {
try {
const bknd = await getBknd();
return bknd.fetch(e.request);
} catch (e) {
return new Response(e.message, { status: 500 });
}
})()
);
}
});