mirror of
https://github.com/Sendouc/sendou.ink.git
synced 2026-08-22 11:05:09 -05:00
Events endpoint working example
This commit is contained in:
32
server/events.ts
Normal file
32
server/events.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type { Express } from "express";
|
||||
|
||||
export function setUpEvents(app: Express): void {
|
||||
// https://stackoverflow.com/a/59041709
|
||||
app.get("/events", (_req, res) => {
|
||||
res.setHeader("Cache-Control", "no-cache");
|
||||
res.setHeader("Content-Type", "text/event-stream");
|
||||
res.setHeader("Access-Control-Allow-Origin", "*");
|
||||
res.setHeader("Connection", "keep-alive");
|
||||
|
||||
// https://stackoverflow.com/a/69938612
|
||||
// Without this Express compression prevents any messages from being
|
||||
// sent until `res.end()` is called
|
||||
res.setHeader("Cache-Control", "no-cache, no-transform");
|
||||
|
||||
res.flushHeaders();
|
||||
|
||||
let counter = 0;
|
||||
let interValID = setInterval(() => {
|
||||
counter++;
|
||||
console.log("write", counter);
|
||||
res.write(`data: ${JSON.stringify({ num: counter })}\n\n`); // res.write() instead of res.send()
|
||||
}, 1000);
|
||||
|
||||
// If client closes connection, stop sending events
|
||||
res.on("close", () => {
|
||||
console.log("client dropped me");
|
||||
clearInterval(interValID);
|
||||
res.end();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import morgan from "morgan";
|
||||
import path from "path";
|
||||
import { LoggedInUser } from "~/validators/user";
|
||||
import { setUpAuth } from "./auth";
|
||||
import { setUpEvents } from "./events";
|
||||
import { setUpMockAuth } from "./mock-auth";
|
||||
import { setUpSeed } from "./seed";
|
||||
|
||||
@@ -15,6 +16,7 @@ const MODE = process.env.NODE_ENV;
|
||||
const BUILD_DIR = path.join(process.cwd(), "server/build");
|
||||
|
||||
const app = express();
|
||||
app.disable("x-powered-by");
|
||||
app.use(compression());
|
||||
|
||||
// You may want to be more aggressive with this caching
|
||||
@@ -31,6 +33,7 @@ try {
|
||||
setUpAuth(app);
|
||||
setUpMockAuth(app, mockUserFromHTTPCall);
|
||||
setUpSeed(app);
|
||||
setUpEvents(app);
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user