如果现有服务分别支持以下 GraphQL 查询:
查询某人的银行账户:
query {
balance(id: "1") {
checking
saving
}
}
结果
{
"data": {
"balance": {
"checking": "800",
"saving": "3000"
}
}
}
查询某人的挂单:
query {
pending_order(id: "1") {
books
tickets
}
}
结果
{
"data": {
"pending_order": {
"books": "5",
"tickets": "2"
}
}
}
实现上述功能的源代码是这样的:
module.exports = new GraphQLObjectType({
name: 'Query',
description: 'Queries individual fields by ID',
fields: () => ({
balance: {
type: BalanceType,
description: 'Get balance',
args: {
id: {
description: 'id of the person',
type: GraphQLString
}
},
resolve: (root, { id }) => getBalance(id)
},
pending_order: {
type: OrderType,
description: 'Get the pending orders',
args: {
id: {
description: 'id of the person',
type: GraphQLString
}
},
resolve: (root, { id }) => getPendingOrders(id)
}
})
});
现在,我想让我的 GraphQL 服务架构支持人员级别的架构,即
query {
person (id: "1") {
balance
pending_order
}
}
并得到以下结果:
{
"data": {
"balance": {
"checking": "800",
"saving": "3000"
}
"pending_order": {
"books": "5",
"tickets": "2"
}
}
}
如何重新构建架构,以及如何重用现有的查询服务?
编辑(阅读丹尼尔里尔登的回答后):
我们可以优化 GraphQL 服务,以便我们根据查询进行服务调用吗?即,如果传入的查询是
query {
person (id: "1") {
pending_order
}
}
我的实际查询变为
person: {
...
resolve: (root, { id }) => Promise.all([
getBalance(id)
]) => ({ balance})
}