【发布时间】:2019-10-03 21:09:37
【问题描述】:
我有以下 REST 端点:
/orders/{id}
returns {
orderId,
orderItem,
customerId
}
/customers/{id}
returns {
customerId,
firstName,
lastName
}
我受到这两个端点的限制,它们将被包装在我的 graphql 架构中。
我想要以下架构:
type Order {
orderId: ID!,
orderItem: String,
customer: Customer
}
type Customer{
customerId: ID!
firstName: String!
lastName: String!
}
type Query {
getOrder(id: String!): Order,
getCustomer(id: String!): Customer
}
我想知道是否可以让 GraphQL 解析 Order 类型中的 Customer 对象?我了解您不能将查询的结果传递给另一个查询的参数。
我认为getOrder的解析器是:
const getOrderResolver = axios.get(`/orders/${id}`)
.then((ordersRes) => {
let customerId;
if(ordersRes.data.customerId !== null) {
customerId = ordersRes.data.customerId
axios.get(`/customers/${customerId}`)
.then((customerRes) => ({
return {
orderId: ordersRes.data.orderId
orderItem: ordersRes.data.orderItem
customer: {
customerId: customerRes.data.customerId
firstName: customerRes.data.firstName
lastName: customerRes.data.lastName
}
}
})
} else {
return {
orderId: ordersRes.data.orderId
orderItem: ordersRes.data.orderItem
customer: null
}
}
})
})
getCustomer解析器
const getCustomerResolver = axios.get(`/customers/${customerId}`)
.then((customerRes) => ({
return {
customerId: customerRes.data.customerId
firstName: customerRes.data.firstName
lastName: customerRes.data.lastName
}
})
似乎在我的解决方案中,无论是否在 getOrder 查询中查询,始终获取 Customer 类型都会产生额外的成本。是否可以重写我的 GraphQL 架构,使 GraphQL 仅在查询时才能解析 Customer 类型?
由于Customer API 需要customerId,因此我的ORDERS REST API 仅返回CustomerId 的限制使得在getOrder 中难以解决
【问题讨论】:
-
您是如何构建架构的?您是直接调用 GraphQLSchema 构造函数还是使用像
buildSchema或makeExecutableSchema这样的实用函数?还是模式创建与您正在使用的其他库(例如 Apollo Server)相结合? -
我通过
graphql-tools使用makeExecutableSchema并通过 Apollo Server 提供服务。
标签: javascript ecmascript-6 graphql