refactor: Update dependencies and refactor code (#18)

* refactor: Update dependencies and refactor code

Removed axios-web and replaced with BroadcastChannel and WebSocket for counter and global count functionalities.

* feat: Update CounterCard and routes

Update CounterCard timeout and routes POST method

* Debug socket message

* ensure value is always treated as a BigInt internally

* Frogot to put it below that 💀

* Move type conversion to database

* I swear if this doesnt work im going to choke someone

* assign converted value to a variable

SURELY this will work right?

* Revert db to use numbers again
This commit is contained in:
Ayase Minori 2023-10-24 00:11:50 +08:00 committed by GitHub
parent 06ba0c3dfc
commit 41be1559f1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 31 additions and 34 deletions

View file

@ -21,8 +21,7 @@
"@twind/preset-tailwind": "https://esm.sh/@twind/preset-tailwind@1.1.4",
"@twind/preset-autoprefix": "https://esm.sh/@twind/preset-autoprefix@1.0.7",
"$std/": "https://deno.land/std@0.193.0/",
"$gfm": "https://deno.land/x/gfm@0.2.3/mod.ts",
"axios-web": "https://esm.sh/axios@1.3.2?target=es2022"
"$gfm": "https://deno.land/x/gfm@0.2.3/mod.ts"
},
"compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "preact" },
"exclude": ["**/_fresh/*"]

View file

@ -1,6 +1,5 @@
import { Button } from "../components/Button.tsx";
import { useEffect, useState } from "preact/hooks";
import axios from "axios-web";
interface SharedProps {
globalCount: bigint;
@ -50,6 +49,7 @@ export default function Counter(props: SharedProps) {
);
const [internalCount, setInternalCount] = useState(0);
const [timer, setTimer] = useState(0);
const ipc = new BroadcastChannel("counterIpc");
const onClick = () => {
setInternalCount(internalCount + 1);
@ -84,10 +84,7 @@ export default function Counter(props: SharedProps) {
setCount(0);
setInternalCount(0);
} else {
axios.post(
window.location.href,
JSON.stringify({ data: internalCount + 1 }),
);
ipc.postMessage(internalCount + 1);
console.info(
`[${new Date().toISOString()}] Updating global count: ${
internalCount + 1
@ -95,7 +92,7 @@ export default function Counter(props: SharedProps) {
);
setInternalCount(0);
}
}, 5000));
}, 2048));
};
const handleWSEvents = (ws: WebSocket) => {
@ -153,6 +150,10 @@ export default function Counter(props: SharedProps) {
handleWSEvents(ws);
ipc.addEventListener("message", (e) => {
ws.send(JSON.stringify({data: e.data}));
});
const onlineHandler = () => {
console.log("Client detected online, resuming connection.");
ws = new WebSocket(window.location.href.replace("http", "ws"));
@ -161,20 +162,20 @@ export default function Counter(props: SharedProps) {
const offlineHandler = () => {
console.warn("Client detected offline!");
ws.close();
ws!.close();
};
globalThis.window.addEventListener("online", onlineHandler);
globalThis.window.addEventListener("offline", offlineHandler);
globalThis.window.addEventListener("beforeunload", () => {
ws.close();
ws!.close();
});
return () => {
globalThis.window.removeEventListener("online", onlineHandler);
globalThis.window.removeEventListener("offline", offlineHandler);
handleWSEvents(ws);
ws.close();
handleWSEvents(ws!);
ws!.close();
};
}, []);

View file

@ -45,9 +45,20 @@ export const handler: Handlers = {
}
});
socket.onmessage = (e) => {
socket.onmessage = async (e) => {
// client will send 0x0 as a string, send back 0x1 as a string to confirm the connection is alive
if (e.data === (0x0).toString()) socket.send((0x1).toString());
if (e.data === (0x0).toString()) {
socket.send((0x1).toString());
} else {
const reqNewCount = JSON.parse(e.data);
// check against MAX_SAFE_INTEGER. Ignore if it's larger than that
if (reqNewCount.data >= Number.MAX_SAFE_INTEGER && Number.isNaN(reqNewCount)) return;
await setGlobalStatistics(reqNewCount.data);
const newCount = await getGlobalStatistics();
bc.postMessage(newCount.toString());
}
};
socket.onclose = () => {
@ -75,7 +86,7 @@ export const handler: Handlers = {
const res = await ctx.render({ globalCount: data });
return res;
},
POST: async (req, ctx) => {
POST: async (req) => {
const body = await req.json();
const headers = req.headers;
@ -96,24 +107,10 @@ export const handler: Handlers = {
});
}
await setGlobalStatistics(body.data);
const updatedCount = await getGlobalStatistics();
const bc = new BroadcastChannel("global-count");
bc.postMessage(updatedCount.toString());
// log the request
console.log(
`[${
new Date().toISOString()
}] Updated global count to ${updatedCount} from ${
JSON.stringify(ctx.remoteAddr)
} (UA: ${headers.get("user-agent")})})`,
);
// ha you thought this is an endpoint
return new Response("", {
status: 200,
statusText: "OK",
status: 410,
statusText: "💀",
});
},
};

View file

@ -1,11 +1,11 @@
const kv = await Deno.openKv();
export async function getGlobalStatistics() {
const res = await kv.get<bigint>(["global-statistics"])!;
const res = await kv.get<number>(["global-statistics"])!;
return res.value!;
}
export async function setGlobalStatistics(value: bigint) {
export async function setGlobalStatistics(value: number) {
const pv = await getGlobalStatistics();
await kv.set(["global-statistics"], pv + value);
}