I didn't know how to title this question but here's what I am uncertain about.
I have a React frontend that is making a GraphQl query to our GraphQl midlayer which aggregates data by making calls to our legacy REST api.
So for example in React I can call the getCustomer
query:
query getCustomer($id: Int!) {
getCustomer(id: $id) {
name
email
}
}
which will hit the getCustomer
resolver which then makes a request to our REST customers/{id}
endpoint to return our data.
async function getCustomer(_, { id }, ctx) {
const customer = await ctx.models.customer.getCustomer(id);
return customer;
}
This request is fine if I am printing a list of customers. But where my questions comes into play is how can I make conditional API requests in my resolver based on data I am querying?
Say each customer can have multiple addresses and these addresses live on a different endpoint. I would love to get those addresses like this in my frontend:
query getCustomer($id: Int!) {
getCustomer(id: $id) {
name
email
address {
city
}
}
}
How could I have my resolver handle this based on my types
and schemas
? Something fundamentally like this:
async function getCustomer(_, { id }, ctx) {
const customer = await ctx.models.customer.getCustomer(id);
[If the query includes the address field]
const addresses = await ctx.models.customer.getAddressesByCustomer(id);
customer.addresses = addresses;
[/If]
return customer;
}
Ultimately, the goal is to have the getCustomer
resolver be capable of returning all customer data across various endpoints based on what fields are sent in the query but not making those additional API requests if the field isn't requested.