Skip to content

Instantly share code, notes, and snippets.

@sahandevs
Created June 10, 2022 14:52
Show Gist options
  • Select an option

  • Save sahandevs/7e0200aff9cf10d0fd0a3af9d024b3d6 to your computer and use it in GitHub Desktop.

Select an option

Save sahandevs/7e0200aff9cf10d0fd0a3af9d024b3d6 to your computer and use it in GitHub Desktop.
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
const data = {};
async function handleRequest(request) {
const { pathname } = new URL(request.url);
if (pathname.startsWith("/get")) {
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" },
});
}
if (pathname.startsWith("/set") && request.method === "POST") {
const deviceName = pathname.split("/")[2];
const x = await request.json();
data[deviceName] = x;
return new Response(JSON.stringify({ status: "OK" }), {
headers: { "Content-Type": "application/json" },
});
}
return new Response("Invalid");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment