Created
March 10, 2020 20:45
-
-
Save kevboutin/6ddbb74a9bc621b73d968c42bd02f3ae to your computer and use it in GitHub Desktop.
Sending messages to a queue using Azure Service Bus
This file contains hidden or 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
const { ServiceBusClient } = require('@azure/service-bus'); | |
const moment = require('moment'); | |
const connectionString = process.env.SB_CONNECTION; | |
const queueName = process.env.SB_QUEUE_NAME; | |
const listOfScientists = [ | |
{ | |
id: 1, | |
name: "Einstein", | |
firstName: "Albert" | |
}, | |
{ | |
id: 2, | |
name: "Heisenberg", | |
firstName: "Werner" | |
}, | |
{ | |
id: 3, | |
name: "Curie", | |
firstName: "Marie" | |
}, | |
{ | |
id: 4, | |
name: "Hawking", | |
firstName: "Steven" | |
}, | |
{ | |
id: 5, | |
name: "Newton", | |
firstName: "Isaac" | |
}, | |
{ | |
id: 6, | |
name: "Bohr", | |
firstName: "Niels" | |
}, | |
{ | |
id: 7, | |
name: "Faraday", | |
firstName: "Michael" | |
}, | |
{ | |
id: 8, | |
name: "Galilei", | |
firstName: "Galileo" | |
}, | |
{ | |
id: 9, | |
name: "Kepler", | |
firstName: "Johannes" | |
}, | |
{ | |
id: 10, | |
name: "Kopernikus", | |
firstName: "Nikolaus" | |
} | |
]; | |
/** | |
* Sending messages to service bus queue. | |
* | |
* @param {object} context The context. | |
* @param {object} req The request. | |
* @returns {Promise<void>} A promise. | |
*/ | |
const sendMessagesHandler = async (context, req) => { | |
context.log(`Sending messages to queue.`, req); | |
const sbClient = ServiceBusClient.createFromConnectionString(connectionString); | |
// If sending to a Topic, use `createTopicClient` instead of `createQueueClient` | |
const queueClient = sbClient.createQueueClient(queueName); | |
const sender = queueClient.createSender(); | |
try { | |
for (let index = 0; index < listOfScientists.length; index++) { | |
const scientist = listOfScientists[index]; | |
const now = moment().format(); | |
const message = { | |
body: { | |
fullName: `${scientist.firstName} ${scientist.name}`, | |
id: scientist.id, | |
label: "Scientist", | |
time: now | |
} | |
}; | |
context.log(`Sending message: ${message.body.time}: ${message.body.id} - ${message.body.fullName} - ${message.body.label}`); | |
await sender.send(message); | |
} | |
await queueClient.close(); | |
} catch (error) { | |
context.log(`Caught an error trying to send messages or closing the queue.`, error); | |
} finally { | |
await sbClient.close(); | |
} | |
}; | |
module.exports = sendMessagesHandler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment