ballerina-platform / ballerina-library

The Ballerina Library
https://ballerina.io/learn/api-docs/ballerina/
Apache License 2.0
137 stars 59 forks source link

[Constraint] Allow constraint annotations on function parameters #4341

Open TharmiganK opened 1 year ago

TharmiganK commented 1 year ago

Description:

Currently we can only add the constraint annotations on type and record field. So in the case of data-binding, users are required to create a new type to add the constraint annotations and use it as the function parameter. For example:

@constraint:String { pattern: re`[0-9]{6}[A-Z|a-z]` }
public type Id string;

service on new http:Listener(9090) {

    resource function post ids(@http:Payload Id id) returns http:Created {
         return http:CREATED;
    }
}

Describe your problem(s)

Rather than having a separate type users should be able to add the annotation in the function signature like this :

service on new http:Listener(9090) {

    resource function post ids(@http:Payload @constraint:String{ pattern: re`[0-9]{6}[A-Z|a-z]` } string id) returns http:Created {
         return http:CREATED;
    }
}

Note : This would be very helpful if we are allowing constraint validations for path parameters, query parameters and header parameters.

Describe your solution(s)

In order to achieve this constraint annotations should be allowed in function parameters and the annotation should be populated to the parameter.

TharmiganK commented 1 year ago

We could allow this by adding support to have annotation in parameter attachment point. But this might not be useful incase of the constraint module's validate function as we the function depends on the type descriptor and having an annotation in line will not be populated to the type:

function test(@constraint:Int{minValue: 10} int id) returns int|error {
     return check constraint:validate(id); // validate the id against the return type `int`
}

// Even if we allow the constraint annotation in the return type, it won't be useful
function test(int id) returns (@constraint:Int{minValue: 10} int)|error {
     // validate the id against the type `int`, annotation is not binded to the type
     return check constraint:validate(id);

}

But this would be useful if we call the validate from the java native function with the parameter type(we can get the annotation and populate it to the type and call native validate)

Also we need to add compiler plugin support for this as well since we do the type tag check and some of the field checks using the compiler plugin.