add server sent events
This commit is contained in:
27
src/realtime/realtime.route.ts
Normal file
27
src/realtime/realtime.route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
||||
import { ChangeEvent, dbEvents } from "../realtime";
|
||||
import { hasValidClaims } from "../auth";
|
||||
|
||||
export async function realTimeRoutes(fastify: FastifyInstance) {
|
||||
fastify.get("/events", async (req: FastifyRequest, res: FastifyReply) => {
|
||||
if (!req.user.role) {
|
||||
return res.code(401).send({ error: "not authorized" });
|
||||
}
|
||||
|
||||
res.raw.setHeader("Content-Type", "text/event-stream");
|
||||
res.raw.setHeader("Cache-Control", "no-cache");
|
||||
res.raw.setHeader("Connection", "keep-alive");
|
||||
res.raw.flushHeaders();
|
||||
|
||||
dbEvents.on("change", (event: ChangeEvent) => {
|
||||
if (hasValidClaims(req.user, event.requiredClaims)) {
|
||||
delete event.requiredClaims;
|
||||
res.raw.write(JSON.stringify(event));
|
||||
}
|
||||
});
|
||||
|
||||
req.raw.on("close", () => {
|
||||
res.raw.end();
|
||||
});
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user