Skip to content

Instantly share code, notes, and snippets.

@Marxpark
Created May 21, 2020 21:53
Show Gist options
  • Save Marxpark/a5a7b15697140b3173c68fe71aebf768 to your computer and use it in GitHub Desktop.
Save Marxpark/a5a7b15697140b3173c68fe71aebf768 to your computer and use it in GitHub Desktop.
connecting msRouter to rabbit
const express = require("express")
const socketIO = require('socket.io');
const http = require('http')
var rabbit = require('amqplib/callback_api');
const pino = require('pino');
require('dotenv').config();
const LOGGER = pino({ level: process.env.LOG_LEVEL || 'info' });
LOGGER.info("Starting server")
let server = http.createServer(express())
let io = socketIO(server)
LOGGER.info(`Connecting to RabbitMQ`)
rabbit.connect('amqp://localhost', (error0, connection) => {
if (error0) {
throw error0;
}
LOGGER.info("Creating default channel on default exchange")
connection.createChannel((error, channel) => {
if (error) {
throw error;
}
rabbit.channel = channel
channel.assertQueue("userLogin", {
durable: false
})
channel.assertQueue("frontendMessage", {
durable: false
})
channel.send = (queue, message) => {
channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)))
}
LOGGER.info("Attaching consumers...")
channel.consume("frontendMessage", (event) => {
console.log(JSON.parse(event.content.toString()))
}, {
noAck: true
})
LOGGER.info("All consumers ready")
})
});
// allow all cors stuff
io.origins('*:*')
io.on('connection', (socket)=>{
LOGGER.debug(`New user connected ${socket.id}`)
socket.on("message", (data) => {
let event = JSON.parse(data)
LOGGER.debug(event)
rabbit.channel.send("userLogin", event)
})
});
server.listen(process.env.INTERNAL_API_PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment