node.jsazureazureservicebusazure-servicebus-topics

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


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?


Solution

  • 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.