Skip to content

Instantly share code, notes, and snippets.

@roguh
Created January 26, 2021 23:04
Show Gist options
  • Save roguh/9c220782640279d040ee563c23300432 to your computer and use it in GitHub Desktop.
Save roguh/9c220782640279d040ee563c23300432 to your computer and use it in GitHub Desktop.
const env = require('env-var')
const Timeout = require('await-timeout')
const { connect, JSONCodec } = require('nats')
const NATS_AUTH_TOKEN = env
.get('NATS_AUTH_TOKEN')
.required()
.asString()
const NATS_URL = env
.get('NATS_URL')
.required()
.asString()
async function natsInit () {
return await connect({
url: NATS_URL,
name: 'powerflex-cloud-edge-device-manager',
timeout: 500,
token: NATS_AUTH_TOKEN
})
}
async function natsPubSubTest (nc) {
const testMessage = 'test-message'
const testChannel = 'test'
const receivedMessages = []
const jsonCodec = JSONCodec()
console.log(`subscribing to ${testChannel}`)
const testSub = await nc.subscribe(testChannel, (err, msg) => {
if (err) {
console.log(err)
} else receivedMessages.push(jsonCodec.decode(msg.data))
})
console.log(`publishing to ${testChannel}`)
nc.publish(testChannel, jsonCodec.encode(testMessage))
nc.flush()
await Timeout.set(2000)
const testPassed = receivedMessages.includes(testMessage)
testSub.unsubscribe()
if (!testPassed) {
throw new Error(`test publish and subscribe failed. messages received: ${receivedMessages}`)
} else console.log('test passed :D')
}
process.on('unhandledRejection', err => console.error(err))
natsInit().then(natsPubSubTest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment