Skip to content

Commit 1ed1d60

Browse files
committed
add server sent events endpoint
1 parent b2db83e commit 1ed1d60

File tree

3 files changed

+50
-511
lines changed

3 files changed

+50
-511
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
},
1818
"dependencies": {
1919
"@well-known-components/env-config-provider": "^1.1.1",
20-
"@well-known-components/http-server": "^1.1.6-20220927190058.commit-2dfb235",
20+
"@well-known-components/http-server": "^2.0.0",
2121
"@well-known-components/interfaces": "^1.4.1",
2222
"@well-known-components/logger": "^3.1.2",
2323
"@well-known-components/metrics": "^2.0.1-20220909150423.commit-8f7e5bc"

src/controllers/routes.ts

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,41 @@
11
import { Router } from "@well-known-components/http-server"
2-
import { GlobalContext } from "../types"
2+
import { GlobalContext, HandlerContextWithPath } from "../types"
33
import { pingHandler } from "./handlers/ping-handler"
4+
import { Readable } from "node:stream"
45

56
// We return the entire router because it will be easier to test than a whole server
67
export async function setupRouter(globalContext: GlobalContext): Promise<Router<GlobalContext>> {
78
const router = new Router<GlobalContext>()
89

910
router.get("/ping", pingHandler)
11+
router.get("/sse", async function (ctx: Pick<HandlerContextWithPath<"metrics", "/sse">, "url" | "components">) {
12+
const stream = new Readable({
13+
read() {
14+
// this fn is called every time the readable "needs" a message
15+
},
16+
construct() {
17+
console.log('constructed')
18+
setInterval(() => this.push(`data: ${JSON.stringify({ now: performance.now() })}\n\n`), 1500)
19+
},
20+
destroy() {
21+
console.log('destroyed')
22+
}
23+
})
24+
25+
26+
27+
// Tell the client to retry every 10 seconds if connectivity is lost
28+
stream.push('retry: 10000\n\n');
29+
30+
return {
31+
headers: {
32+
'Cache-Control': 'no-cache',
33+
'Content-Type': 'text/event-stream',
34+
'Connection': 'keep-alive'
35+
},
36+
body: stream
37+
}
38+
})
1039

1140
return router
1241
}

0 commit comments

Comments
 (0)