Back to Examples

RabbitMQ client - Constraint validation

The Ballerina constraint module allows you to add additional constraints to the message content. The constraints can be added to a given data type using different annotations. When a message with a constraint is received from the RabbitMQ server, it is validated internally. This validation happens soon after the successful data-binding of the message content before returning the message record. If the validation fails, the rabbitmq:PayloadValidationError error is returned. Use this to validate the message content as the application receives it, which allows you to guard against unnecessary message content processing and malicious content.

import ballerina/constraint;
import ballerinax/rabbitmq;
import ballerina/log;

public type Order record {
    int orderId;
    // Add a constraint to allow only string values of length between 1 and 30.
    @constraint:String {maxLength: 30, minLength: 1}
    string productName;
    decimal price;
    boolean isValid;
};

public function main() returns error? {
    // Creates a ballerina RabbitMQ client.
    rabbitmq:Client newClient = check new (rabbitmq:DEFAULT_HOST, rabbitmq:DEFAULT_PORT);

    // Consuming message from the routing key OrderQueue.
    Order|rabbitmq:PayloadValidationError|rabbitmq:Error 'order = newClient->consumePayload("OrderQueue");
    if 'order is Order {
        if 'order.isValid {
            log:printInfo(string `Received valid order for ${'order.productName}`);
        } 
    } else if 'order is rabbitmq:PayloadValidationError {
        log:printError("Payload validation failed", 'order);
    } else {
        log:printError("Error occurred while consuming");    
    }
}

Prerequisites

Run the client program by executing the following command.

$ bal run rabbitmq_client_constraint_validation.baltime = 2022-12-05T08:18:09.346+05:30 level = INFO module = "" message = "Received valid order for Sport shoe"time = 2022-12-05T08:18:49.844+05:30 level = ERROR module = "" message = "Payload validation failed" error = "Validation failed for \'$.productName:maxLength\' constraint(s)."time = 2022-12-05T08:19:19.214+05:30 level = INFO module = "" message = "Received valid order for Sport shoe"

Tip: You can invoke the above service via the RabbitMQ client example with a valid product name (0 < length <= 30), then with an invalid product name and again with a valid product name.

Related links

PreviousTransactional producer
NextSSL/TLS