Last active
April 11, 2016 15:05
-
-
Save apeace/b5c0ee50bdd5a437e76765e9e920c568 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const PubNub = require('pubnub'); | |
const PUBNUB_PUBLISH = process.env.PUBNUB_PUBLISH; | |
const PUBNUB_SUBSCRIBE = process.env.PUBNUB_SUBSCRIBE; | |
const TIMEOUT = 5000; | |
const msg = String(+new Date); | |
console.log('Message: %s', msg); | |
setTimeout(() => { | |
console.log('Didn\'t receive message!'); | |
process.exit(); | |
}, TIMEOUT); | |
let pubnub = PubNub({ | |
ssl: true, | |
publish_key: PUBNUB_PUBLISH, | |
subscribe_key: PUBNUB_SUBSCRIBE | |
}); | |
pubnub.publish({ | |
channel: 'andrew-test', | |
message: msg, | |
success: () => { | |
console.log('Message sent'); | |
subscribe(); | |
}, | |
error: (err) => { | |
console.error('Message not sent', err); | |
process.exit(); | |
} | |
}); | |
function subscribe () { | |
pubnub.subscribe({ | |
channel: 'andrew-test', | |
connect: () => { | |
console.log('Subscribed to channel'); | |
checkHistory(); | |
}, | |
callback: (message) => { | |
if (message === msg) { | |
console.log('Got message from channel!'); | |
process.exit(); | |
} | |
console.log('Channel: %s', message); | |
}, | |
error: (err) => { | |
console.error('Could not subscribe', err); | |
process.exit(); | |
} | |
}); | |
} | |
function checkHistory () { | |
console.log('Checking history'); | |
pubnub.history({ | |
channel: 'andrew-test', | |
callback: (messages) => { | |
for (let message of messages[0]) { | |
message = String(message); | |
console.log('History: %s', message); | |
if (message === msg) { | |
console.log('Got message from history!'); | |
process.exit(); | |
} | |
} | |
}, | |
error: (err) => { | |
console.error('Could not get history', err); | |
process.exit(); | |
}, | |
count: 10, | |
reverse: false | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment