-
Notifications
You must be signed in to change notification settings - Fork 13
/
events.js
39 lines (36 loc) · 948 Bytes
/
events.js
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
const crypto = require('node:crypto')
let clients = []
const handleEvents = (request, response) => {
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache'
}
response.writeHead(200, headers)
const clientId = crypto.randomUUID()
const newClient = {
id: clientId,
response
}
clients.push(newClient)
request.on('close', () => {
console.log(`${clientId} Connection closed`)
clients = clients.filter(client => client.id !== clientId)
})
}
function notifyArticleStatusChange (article) {
clients.forEach(client => {
client.response.write(`data: ${JSON.stringify({
articleStateUpdated: {
collaborativeSession: article.collaborativeSession,
soloSession: article.soloSession,
title: article.title,
_id: article._id
}
})}\n\n`)
})
}
module.exports = {
handleEvents,
notifyArticleStatusChange
}