从 Ballerina 资源函数返回记录

Return record from Ballerina resource function

提问人:Kavindu Gimhan Zoysa 提问时间:11/15/2023 更新时间:11/15/2023 访问量:22

问:

请考虑以下芭蕾舞女演员服务。

import ballerina/http;

public type Tool readonly & record {|
    string name;
    string api_path;
    ToolInput[] inputs;
|};

public type ToolInput readonly & record {|
    string name;
    boolean required;
    any default_value = ();
    any[] allowed_values = ["any"];
|};


public final table<Tool> key(name) toolsTable = table [
    {
        name: "deploy", 
        api_path: "deploy", 
        inputs: [
            {name: "environment", required: true},
            {name: "service", required: true},
            {name: "version", required: false, default_value: "master"},
            {name: "version_type", required: false, default_value: "branch", allowed_values: ["branch", "commit_id", "build_number"]}        
        ]
    }
];

service /foo on new http:Listener(9090) {

    resource function get list\-tools() returns Tool[] {
        return toolsTable.toArray();
    }   
}

当从资源函数返回数组时,我们得到错误 。Tool[]invalid resource method return type: expected anydata|http:Response|http:StatusCodeResponse|error, but found Tool[]

从资源函数返回 Ballerina 记录时有哪些限制?

HTTP 服务 芭蕾舞女演员

评论


答:

1赞 Kavindu Gimhan Zoysa 11/15/2023 #1

正如错误消息中提到的,我们只能返回属于 、 或 之一的类型。根据上面的例子,返回类型应该属于 但是记录包含两个字段,其中类型是 。由于这个原因,不属于.简单地说,我们可以将这些字段的类型更改为如下所示。anydatahttp:Responsehttp:StatusCodeResponseerrorTool[]anydataToolanyTool[]anydataanydata

import ballerina/http;

public type Tool readonly & record {|
    string name;
    string api_path;
    ToolInput[] inputs;
|};

public type ToolInput readonly & record {|
    string name;
    boolean required;
    anydata default_value = ();
    anydata[] allowed_values = ["any"];
|};


public final table<Tool> key(name) toolsTable = table [
    {
        name: "deploy", 
        api_path: "deploy", 
        inputs: [
            {name: "environment", required: true},
            {name: "service", required: true},
            {name: "version", required: false, default_value: "master"},
            {name: "version_type", required: false, default_value: "branch", allowed_values: ["branch", "commit_id", "build_number"]}        
        ]
    }
];

service /foo on new http:Listener(9090) {

    resource function get list\-tools() returns Tool[] {
        return toolsTable.toArray();
    }   
}