Neeraj Kashyap
Neeraj Kashyap

Reputation: 130

Composing GraphQL queries

Suppose a GraphQL schema supports the following queries:

{
    person(id: String) {
        locationId
    }
}

and

{
    location(id: String) {
        country
    }
}

Is it possible to find a person by id, then use the resulting locationid to find their location by id (returning the country corresponding to that location) all the in a single query?

Or would I have to make two separate queries?

Upvotes: 4

Views: 1832

Answers (2)

Alex Anderson
Alex Anderson

Reputation: 670

The query would look like this;

{
    person(id: string){
        location{
            country
        }
    }
}

In your person type, you can apply a resolver to the location field which gets the location based on the locationId of the person which the query is performed against.

Upvotes: 5

MikeRalphson
MikeRalphson

Reputation: 2393

If that is the only information on a location that you can get from a person then yes, you will need to perform two queries in separate requests.

It would be more normal for a GraphQL schema to present the whole location node as visible from the person (i.e. the id's would be dereferenced, though perhaps still available), and if a person could have more than one location then you would follow the locations edge to get to each location node.

Upvotes: 3

Related Questions