-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
69 lines (56 loc) · 1.99 KB
/
server.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
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const {Server} = require("socket.io");
const io = new Server(server);
const amqp = require('amqplib');
// ----- cors -----
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
});
// ----- RabbitMQ & Make QUEUE -----
const QUEUE_NAME = 'notifications';
async function connectRabbitMQ() {
try {
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
// 1. Make queue
await channel.assertQueue(QUEUE_NAME, {durable: false});
// 2. Consume
channel.consume(QUEUE_NAME, (message) => {
io.emit('notification', "message from nodejs");
}, {noAck: true});
// 3. Route sent message
app.post('/send-notification', async (req, res) => {
try {
channel.sendToQueue(QUEUE_NAME, Buffer.from(JSON.stringify({message: "Hi Van Anh"})));
res.status(200).send('Notification sent successfully');
} catch (error) {
console.error('Error sending notification', error);
res.status(500).send('Failed to send notification');
}
});
} catch (error) {
console.error('Error connecting to RabbitMQ', error);
}
}
connectRabbitMQ().then(r => {});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/rabbit-mq', (req, res) => {
res.sendFile(__dirname + '/rabbit-mq.html');
});
// socket (demo 1)
io.on('connection', (socket) => {
socket.on('chat message', (title, name, time) => {
io.emit('chat message', title, name, time);
});
});
server.listen(3002, () => {
console.log('listening on http://localhost:3002');
});