从 Ballerina 资源函数返回记录

问题描述 投票:0回答:1

请考虑以下芭蕾舞服务。

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 service ballerina
1个回答
0
投票

正如错误消息中提到的,我们只能返回属于

anydata
http:Response
http:StatusCodeResponse
error
之一的类型。根据上面的例子,返回类型
Tool[]
应该属于
anydata
但是
Tool
记录包含两个类型为
any
的字段。因此,
Tool[]
不属于
anydata
。我们只需将这些字段的类型更改为
anydata
,如下所示。

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();
    }   
}
© www.soinside.com 2019 - 2024. All rights reserved.