Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pusher's Channels interaction
const PusherServer = require('pusher');
const PusherClient = require('pusher-js');
const express = require('express');
const router = express.Router();
const config = require("config");
const pusherServer = new PusherServer(config.get('pusher.config'));
const pusherClient = new PusherClient(config.get('pusher.config.key'), {
cluster: config.get('pusher.config.cluster')
})
/* POST main api for a processing job. */
router.post('/', function(req, res, next) {
//code require to receive the message, parse it
//and maybe validate the data?
//then communicate with the processing service through Channels
pusherServer.trigger('main-channel', 'message', {
"message": //... information for other services
});
res.send(/* the response */);
});
function messageHandler(data) {
///your logic to handle new messsages
}
module.exports = function () {
const channel = pusherClient.subscribe('main-channel')
channel.bind('message', messageHandler)
return router;
}
const PusherServer = require('pusher')
const PusherClient = require("pusher-js")
const config = require("config")
const pusherServer = new PusherServer(config.get('pusher.config'));
const pusherClient = new PusherClient(config.get('pusher.config.key'), {
cluster: config.get('pusher.config.cluster')
})
const HB_TIMEOUT = 10100;
let TIMEOUTS = {}
// your routes definition goes here...
function sendHeartBeat(modId) {
console.log("Sending hearbeat: ", Date.now())
pusherServer.trigger(modId + '-hb', 'heartbeat', {
"message": {
"timestamp": Date.now(),
"payload": ""///other data goes here
}
}, null, (err, req, resp) => {
if(err) console.log("Error:: ", err)
})
}
function handleHearbeat(serviceName) {
return function () {
///your logic to handle hearbeats
clearTimeout(TIMEOUTS[serviceName]) //reset the timeout in case we actually get a hearbeat before it's up
console.log("Hearbeat received from Module '" + serviceName + "' at: ", Date.now())
TIMEOUTS[serviceName] = setTimeout(heartBeatNotReceived, HB_TIMEOUT, serviceName)
}
}
function heartBeatNotReceived(serviceName) {
console.log("WARNING: Module ='" + serviceName + "'= has not sent a heartbeat recently...")
}
module.exports = function(modId, linkedServices) {
linkedServices.forEach((serviceName) => {
let channel = pusherClient.subscribe(serviceName + '-hb')
channel.bind('heartbeat', handleHearbeat(serviceName))
})
setInterval(sendHeartBeat, 10000, modId); //send one every 10 seconds
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment