-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (82 loc) · 1.78 KB
/
index.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
var URL = require('url')
var concat = require('concat-stream')
var SSEClient = require('sse').Client
/**
* Register new client
*
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
* @param {Object} clients
* @param {*} id
*/
function registerClient(req, res, clients, id)
{
var client = new SSEClient(req, res)
client.on('close', function()
{
delete clients[id]
})
client.initialize()
clients[id] = client
}
/**
* Forward the notification to the client
*
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
* @param {SSEClient} client
*/
function fordwardNotification(req, res, client)
{
req.pipe(concat(function(body)
{
client.send(body.toString())
res.end()
}))
}
/**
*
*/
function post2sse()
{
var clients = {}
/**
* Process incoming requests
*
* @param {http.IncomingMessage} req
* @param {http.ServerResponse} res
*/
return function(req, res)
{
var id = URL.parse(req.url).pathname.substr(1)
if(!id)
{
res.statusCode = 403
return res.end()
}
var client = clients[id]
switch(req.method)
{
// SSE EventSource registrations
case 'GET':
// Register new client
if(!client) return registerClient(req, res, clients, id)
// Client ID already being used
res.statusCode = 409
break
// Incoming notifications
case 'POST':
// Forward the notification to the client
if(client) return fordwardNotification(req, res, client)
// Client not found
res.statusCode = 404
break
// Unknown method
default:
res.statusCode = 405
}
// There was an error with the request, close connection inmediatly
res.end()
}
}
module.exports = post2sse