How to send data to topic endpoint in a azure event grid from NodeJS
I have a topic created in a azure event grid. I need to send SMS message data to it from NodeJS Api call. How can I send it from NodeJS.
CodePudding user response:
To send data to an Azure Event Grid topic from a Node.js application, you can use the Azure Event Grid Node.js SDK. Here is an example of how to do it:
First, install the Azure Event Grid Node.js SDK:
npm install @azure/eventgrid
import the EventGridPublisherClient class from the Azure Event Grid Node.js SDK:
const { EventGridPublisherClient } = require('@azure/eventgrid');
Then, create an instance of the EventGridPublisherClient class, passing in the endpoint and access key for your Event Grid topic as arguments:
const eventGridClient = new EventGridPublisherClient(
'<EVENT_GRID_TOPIC_ENDPOINT>',
'<EVENT_GRID_TOPIC_ACCESS_KEY>'
);
Now, you can send data to your Event Grid topic by calling the sendEvent method on the eventGridClient instance and passing in the event data as an argument. For example, to send an SMS message event, you might do something like this:
const eventData = {
id: '1',
eventType: 'SmsSent',
data: {
phoneNumber: ' 1234567890',
message: 'Hello, world!'
},
subject: 'sms/sent',
eventTime: new Date()
};
eventGridClient.sendEvent(eventData)
.then(() => {
console.log('Event published successfully.');
})
.catch((err) => {
console.error('Error publishing event:', err);
});