I have the following REST endpoints:
/orders/{id}
returns {
orderId,
orderItem,
customerId
}
/customers/{id}
returns {
customerId,
firstName,
lastName
}
I am limited by these two endpoints, which are going to be wrapped in my graphql schema.
I would like the following Schema:
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
}
I'm wondering if it is possible to have GraphQL resolve the Customer object in the Order type? I understand that you cannot pass the result of a query into the parameter of another.
I have considered the resolver of getOrder
be:
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
resolver
const getCustomerResolver = axios.get(`/customers/${customerId}`)
.then((customerRes) => ({
return {
customerId: customerRes.data.customerId
firstName: customerRes.data.firstName
lastName: customerRes.data.lastName
}
})
It seems with my solution, there will be the additional cost of always fetching the Customer
type whether or not it is queried within the getOrder
query. Is it possible to rewrite my GraphQL schema in a way that GraphQL would be able to resolve the Customer
type only when queried?
The limitation of my given my ORDERS
REST API only returns the CustomerId
makes it difficult to resolve in getOrder
, since the Customer
API requires a customerId
buildSchema
ormakeExecutableSchema
? Or is the schema creation coupled with some other library you're using, like Apollo Server? – Daniel ReardenmakeExecutableSchema
viagraphql-tools
and serving it via Apollo Server. – Magnum