Adding custom message properties when creating Service Bus Topic messages with Node.js

43 views Asked by At

I have a topic with multiple subscriptions and need to add a filter to each of the subsbscriptions to trigger a corresponding function app.

Here is my Node.js code to create a message:

const router = express.Router();
const { jsonParser, ServiceBusClient } = require('../server');

const connectionString = process.env.SERVICE_BUS_CONNECTION_STRING;
const topicName = process.env.SERVICE_BUS_TOPIC_NAME;


router.post('/post-message', jsonParser, async (req, res) => {
    try {
        // Extract message data from the request
        const messageData = req.body;
        // Create a Service Bus client using the connection string
        const serviceBusClient = new ServiceBusClient(connectionString);

        // Create a sender for the topic
        const sender = serviceBusClient.createSender(topicName);

        const message = {
            applicationProperties: {
                eventType: "jobCosts"
            },
            subject: 'jobCosts',
            body: messageData,
        };

        console.log(message);

        // Send the message to the topic
        await sender.sendMessages(message);

        // Close the sender and the Service Bus client
        await sender.close();
        await serviceBusClient.close();

        res.send(message);

    } catch (error) {
        console.error("Error sending message to Service Bus topic:", error);
        // Handle the error, e.g., by sending an error response
        res.status(500).json({ error: "An error occurred while sending the message to the topic" });
    }
})

module.exports = router;

And I have a correlation filter configured for a custom property named eventType = "jobCosts".

When I send a message from the Azure Portal using Service Bus Explorer, the message is processed correctly, but when I execute the code above, the message is posted, but never hits the topic.

Have also tried filtering on the label/subject system property by passing 'subject' but can't get that to work either. Anyone know where I'm going wrong?

2

There are 2 answers

0
Octo On BEST ANSWER

I did a comparison of the messages generated by Service Bus Explorer and those generated by my code. Service Bus Explorer wrapped the subject in double quotes where my code did not.

Updating the correlation rule to subject/label equals jobCosts instead of "jobCosts" did the trick and the subscription started picking up the messages I send from my code.

0
Suresh Chikkam On

Have also tried filtering on the label/subject system property by passing 'subject' but can't get that to work either. Anyone know where I'm going wrong?

I had tried the above code, and I had the same issue my messages are sending through the code but those are reaching to dead letter which is not satisfied.

  • I have enabled the session Id to my subscription as shown in below.

enter image description here

Code:

const { ServiceBusClient } = require("@azure/service-bus");
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/send-message', async (req, res) => {
    let serviceBusClient;
    let sender;
    
    try {
        const connectionString = "Endpoint=sb://your-servicebusnamespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=svbfe";
        const topicName = "give-ur-topic-name";

        serviceBusClient = new ServiceBusClient(connectionString);
        sender = serviceBusClient.createSender(topicName);

        // Create a message
        const messageBody = {
            id: 1,
            eventType: "jobCosts",
            // Add other message properties if needed
        };

        const message = {
            body: JSON.stringify(messageBody),
            // Add other message properties if needed
            // For correlation filter, you can set the properties here
            correlationId: "12345", // Optional, you can set this to any unique identifier
            sessionId: "107", // Set the session ID here
        };

        console.log("Sending message:", messageBody);

        // Send the message
        await sender.sendMessages(message);
        console.log("Message sent successfully");

        res.send("Message sent successfully");
    } catch (error) {
        console.error("Error occurred:", error);
        res.status(500).send("Error occurred while sending message");
    } finally {
        try {
            if (sender) {
                await sender.close();
            }
            if (serviceBusClient) {
                await serviceBusClient.close();
            }
        } catch (error) {
            console.error("Error while closing sender or service bus client:", error);
        }
    }
});

app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

enter image description here

  • Below are my two subscriptions one is session enabled and the other is disabled, you can see the active messages count 14 for enabled subscription.

enter image description here

Received messages:

enter image description here