Properly encode responses

This commit is contained in:
Ayase Minori 2023-09-11 04:57:06 +00:00 committed by GitHub
parent 062a03c708
commit 3062eae5a6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 32 additions and 7 deletions

23
.vscode/launch.json vendored Normal file
View file

@ -0,0 +1,23 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"request": "launch",
"name": "Launch Program",
"type": "node",
"program": "${workspaceFolder}/dev.ts",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "/usr/local/bin/deno",
"runtimeArgs": [
"run",
"--inspect-wait",
"--allow-all",
"--unstable"
],
"attachSimplePort": 9229
}
]
}

View file

@ -42,18 +42,18 @@ export default function Counter(props: SharedProps) {
let es = new EventSource(window.location.href);
es.addEventListener("open", () => {
console.log(`[${new Date()}] Connected to statistics stream`);
console.log(`Connected to statistics stream`);
});
es.addEventListener("message", (e) => {
console.log(`[${new Date()}] Received global count: ${e.data}`);
console.log(` Received global count: ${e.data}`);
props.globalCount = e.data;
});
// TODO: Reconnect backoff logic could be improved
es.addEventListener("error", () => {
console.warn(
`[${new Date()}] Disconnected from statistics stream, attempting to reconnect...`,
`Disconnected from statistics stream, attempting to reconnect...`,
);
const backoff = 1000 + Math.random() * 5000;
new Promise((resolve) => setTimeout(resolve, backoff));

View file

@ -13,7 +13,7 @@ export const handler: Handlers = {
start(controller) {
bc.addEventListener("message", () => {
try {
controller.enqueue(getGlobalStatistics.toString());
controller.enqueue(new TextEncoder().encode(getGlobalStatistics().toString()));
} catch (e) {
console.error(`[${new Date()}] Error while getting global statistics: ${e}`);
}
@ -39,11 +39,13 @@ export const handler: Handlers = {
const body = await req.json();
setGlobalStatistics(body.data);
// broadcast new value to everyone
const bc = new BroadcastChannel("global-count");
bc.postMessage(getGlobalStatistics().toString());
bc.postMessage(new TextEncoder().encode(getGlobalStatistics().toString()))
return Response.json({ success: true })
return new Response("", {
status: 200,
statusText: "OK"
})
}
}