-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
101 lines (85 loc) · 2.62 KB
/
app.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
101
var express = require('express')
var bodyParser = require('body-parser')
var rabbitConn = require('./connection')
var app = express()
var router = express.Router()
var server = require('http').Server(app)
var io = require('socket.io')(server)
var chat = io.of('/chat')
rabbitConn(function(conn) {
conn.createChannel(function(err, ch) {
if (err) {
throw new Error(err)
}
var ex = 'chat_ex'
ch.assertExchange(ex, 'fanout', {durable: false})
ch.assertQueue('', {exclusive: true}, function(err, q) {
if (err) {
throw new Error(err)
}
ch.bindQueue(q.queue, ex, '')
ch.consume(q.que, function(msg) {
chat.emit('chat', msg.content.toString())
})
}, {noAck: true})
})
})
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.use('/api', router)
router.route('/chat')
.post(function(req, res) {
rabbitConn(function(conn) {
conn.createChannel(function(err, ch) {
if (err) {
throw new Error(err)
}
var ex = 'chat_ex'
var q = 'chat_q'
var msg = JSON.stringify(req.body)
ch.assertExchange(ex, 'fanout', {durable: false})
ch.publish(ex, '', new Buffer(msg), {persistent: false})
ch.assertQueue(q, {durable: true})
ch.sendToQueue(q, new Buffer(msg), {persistent: true})
ch.close(function() {conn.close()})
})
})
})
.get(function(req, res){
rabbitConn(function(conn){
conn.createChannel(function(err, ch) {
if (err) {
throw new Error(err)
}
var q = 'chat_q'
ch.assertQueue(q, {durable: true}, function(err, status) {
if (err) {
throw new Error(err)
}
else if (status.messageCount === 0) {
res.send('{"messages": 0}')
} else {
var numChunks = 0;
res.writeHead(200, {"Content-Type": "application/json"})
res.write('{"messages": [')
ch.consume(q.que, function(msg) {
var resChunk = msg.content.toString()
res.write(resChunk)
numChunks += 1
numChunks < status.messageCount && res.write(',')
if (numChunks === status.messageCount) {
res.write(']}')
res.end()
ch.close(function() {conn.close()})
}
})
}
})
}, {noAck: true})
})
})
server.listen(3030, '0.0.0.0',
function() {
console.log('Chat at localhost:3030')
}
)