Last active
August 16, 2024 18:35
-
-
Save David256/e75442029cbc0bfab5458cd8015a2bbf to your computer and use it in GitHub Desktop.
short_polling_server.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let powerstatus = "0"; | |
let lastPowerstatus = "0"; | |
const waitForChange = (timeout: number) => { | |
return new Promise<string>((resolve) => { | |
const start = Date.now(); | |
const interval = 100; | |
const check = () => { | |
if (powerstatus !== lastPowerstatus) { | |
lastPowerstatus = powerstatus; | |
resolve(lastPowerstatus); | |
} else if (Date.now() - start >= timeout) { | |
resolve(lastPowerstatus); | |
} else { | |
setTimeout(check, interval); | |
} | |
}; | |
check(); | |
}); | |
}; | |
const server = Bun.serve({ | |
port: 12000, | |
async fetch(request, server) { | |
const url = new URL(request.url); | |
console.log("URL:", url.href); | |
if (url.pathname === "/ask/powerstatus") { | |
if (request.method === "GET") { | |
const value = await waitForChange(10000); | |
return new Response(value); | |
} else if (request.method === "PUT") { | |
const content = await request.text(); | |
if (content === "1" || content === "0") { | |
powerstatus = content; | |
return new Response(content); | |
} | |
} | |
} | |
return Response.redirect("https://www.nasa.gov", 302); | |
}, | |
}); | |
console.log(`Listening on ${server.url}`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment