From 3062eae5a6db255af4c5997ed9957fc99d79b450 Mon Sep 17 00:00:00 2001 From: Ayase Minori Date: Mon, 11 Sep 2023 04:57:06 +0000 Subject: [PATCH] Properly encode responses --- .vscode/launch.json | 23 +++++++++++++++++++++++ islands/CounterCard.tsx | 6 +++--- routes/index.tsx | 10 ++++++---- 3 files changed, 32 insertions(+), 7 deletions(-) create mode 100644 .vscode/launch.json diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..cbe680f --- /dev/null +++ b/.vscode/launch.json @@ -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 + } + ] +} diff --git a/islands/CounterCard.tsx b/islands/CounterCard.tsx index b9ac336..636b542 100644 --- a/islands/CounterCard.tsx +++ b/islands/CounterCard.tsx @@ -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)); diff --git a/routes/index.tsx b/routes/index.tsx index 3905664..adcd7aa 100644 --- a/routes/index.tsx +++ b/routes/index.tsx @@ -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" + }) } }