在Ballerina中使用默认值的记录类型作为GraphQL资源的输入是没有问题的。以下是一个简单的示例,说明如何使用默认值的记录类型作为GraphQL查询的输入参数:
import ballerina/http;
import ballerinax/graphql;
type Book record {
string title;
string author;
string isbn = "N/A";
};
graphql:ServiceConfig serviceConfig = {
schema: `
type Query {
getBook(title: String!, author: String!, isbn: String = "N/A"): Book
}
type Book {
title: String!
author: String!
isbn: String!
}
`,
resolvers: {
Query: {
getBook: remote function(context, title, author, isbn = "N/A") returns Book {
return {title: title, author: author, isbn: isbn};
}
}
}
};
graphql:Client client = new(graphql:GraphQLClientConfig { uri: "http://localhost:9090/graphql" });
public function main() {
http:Listener listener = new(9090);
graphql:Service service = new(serviceConfig);
listener.start(service);
io:println("Server started");
var response = client->execute("query { getBook(title: \"The Alchemist\", author: \"Paulo Coelho\") { title, author, isbn } }");
if (response is graphql:Response) {
io:println(response.getMessageAsString());
} else {
io:println(json:fromTable(Error Description CLIENT_ERROR Invalid response
));
}
}
在上述示例中,Book
类型定义了一个名为isbn
的默认值为“N/A”的字段。在ServiceConfig
中,getBook
函数中的参数isbn
也有一个默认值为“N/A”。在GraphQL查询中,我们可以省略isbn
参数并相应地使用默认值,如下所示:
query { getBook(title: "The Alchemist",