Nuxt is based on Vue.js and I find their building blocks to be much neater compared to the React based Next.js.
47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
import { Schedule } from "~/shared/types/schedule"
|
|
|
|
function sendMessage(
|
|
stream: WritableStream<string>,
|
|
message: string,
|
|
) {
|
|
const writer = stream.getWriter();
|
|
writer.ready
|
|
.then(() => writer.write(message))
|
|
.catch(console.error)
|
|
.finally(() => writer.releaseLock())
|
|
;
|
|
}
|
|
|
|
const streams = new Set<WritableStream<string>>();
|
|
|
|
let keepaliveInterval: ReturnType<typeof setInterval> | null = null
|
|
export function addStream(stream: WritableStream<string>) {
|
|
if (streams.size === 0) {
|
|
console.log("Starting keepalive")
|
|
keepaliveInterval = setInterval(sendKeepalive, 4000)
|
|
}
|
|
streams.add(stream);
|
|
}
|
|
export function deleteStream(stream: WritableStream<string>) {
|
|
streams.delete(stream);
|
|
if (streams.size === 0) {
|
|
console.log("Ending keepalive")
|
|
clearInterval(keepaliveInterval!);
|
|
}
|
|
}
|
|
|
|
export function broadcastUpdate(schedule: Schedule) {
|
|
const id = Date.now();
|
|
const data = JSON.stringify(schedule);
|
|
const message = `id: ${id}\nevent: update\ndata: ${data}\n\n`
|
|
console.log(`broadcasting update from ${process.pid} to ${streams.size} clients`);
|
|
for (const stream of streams) {
|
|
sendMessage(stream, message);
|
|
}
|
|
}
|
|
|
|
function sendKeepalive() {
|
|
for (const stream of streams) {
|
|
sendMessage(stream, "data: keepalive\n\n");
|
|
}
|
|
}
|