-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathserver.ts
44 lines (36 loc) · 860 Bytes
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import path from "node:path";
import {type Session, createSession} from "better-sse";
import express from "express";
const app = express();
app.use(express.static(path.resolve(__dirname, "./public")));
/**
* Needed to make TypeScript recognize the Session object attached to the response object.
*/
declare module "express-serve-static-core" {
interface Response {
sse: Session;
}
}
app.get(
"/sse",
/**
* Attach the session instance to the response.
*/
async (req, res, next) => {
const session = await createSession(req, res);
res.sse = session;
next();
},
/**
* Push a message with the event name "ping".
*/
(_, res) => {
res.sse.push("Hello world!", "ping");
}
);
const PORT = process.env.PORT ?? 8080;
app.listen(PORT, () => {
console.log(
`Server listening. Open http://localhost:${PORT} in your browser.`
);
});