This repository has been archived by the owner on Mar 7, 2018. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #15 from CatalystCode/split-out-eventhub-client
Split out client to send EventHub messages
- Loading branch information
Showing
2 changed files
with
40 additions
and
30 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
const EventHubClient = require('azure-event-hubs').Client; | ||
|
||
const eventHubConnectionString = process.env.PUBLISH_EVENTS_EVENTHUB_CONNECTION_STRING; | ||
const eventHubPath = process.env.PUBLISH_EVENTS_EVENTHUB_PATH; | ||
const eventHubPartition = process.env.PUBLISH_EVENTS_EVENTHUB_PARTITION; | ||
const eventHubClient = EventHubClient.fromConnectionString(eventHubConnectionString, eventHubPath); | ||
|
||
function sendMessages(messages) { | ||
return new Promise((resolve, reject) => { | ||
if (!messages || !messages.length) { | ||
reject('No messages to be sent'); | ||
return; | ||
} | ||
|
||
let payloads; | ||
try { | ||
payloads = messages.map(message => ({contents: JSON.stringify(message)})); | ||
} catch (err) { | ||
reject(`Unable to create payloads for EventHub: ${err}`); | ||
return; | ||
} | ||
|
||
eventHubClient.open() | ||
.then(() => eventHubClient.createSender()) | ||
.then(eventHubSender => { | ||
eventHubSender.on('errorReceived', err => reject(`Error talking to EventHub: ${err}`)); | ||
Promise.all(payloads.map(payload => eventHubSender.send(payload, eventHubPartition))) | ||
.then(() => resolve([])) | ||
.catch((err) => reject(`Error sending EventHub message: ${err}`)); | ||
}); | ||
}); | ||
} | ||
|
||
module.exports = { | ||
sendMessages: sendMessages | ||
}; |
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