Casey
Casey

Reputation: 152

Graphql query object filtering and field subfiltering

Imagine there is a schema like

type Country {
  id String
  name String
  continent String
  languages [Language]
}
type Language {
  id String
  code String
  globalSpeakers Int
}

and I want to query for countries on some continent with some language. And I only want the language field in the country to include the language I'm searching for. So if I wanted countries in Eurasia that spoke French, and didn't want any other languages on the country object...

Is there a recommended way to do this?

Typically I would use a dataloader to batch load the language list on the country, but, as far as I can tell, they really only want to get data by id. So the returned data would have a bunch of languages on the country that I don't want and would need to get rid of on the consumer.

Using one query:

I've thought of trying to get the dataloader (batch loader) to accept arguments other than id, and then trying to batch load by ids and query arguments. Like getting the Country.Language dataloader to accept country id and query args.

I've thought about doing all the querying at the top resolver. But then, in the Country.Language dataloader, I would need to check the country instance, see if it already has language data, and then call or not call the dataloader.

Some other option?

Using multiple queries

I've thought about creating two queries where one can search for countries by criteria and one can search for languages by criteria. And then join the data on the consumer (with potentially some additional filtering).

Some other option?

Upvotes: 0

Views: 713

Answers (1)

Michel Floyd
Michel Floyd

Reputation: 20227

Define a query:

GetCountryByContinentAndLanguage(continent: String, language: String): [Country]

In your query resolver search your database for matches based on the continent and country. This search should yield 0-N countries.

Then in your Country Languages resolver - look at the args - if you see a language variable then only return that single language instead of all the languages for that country.

OTOH, if you're running this search from the client then you already know what language you want and you can just ignore the languages field in the return object and replace it with your single language.

Upvotes: 1

Related Questions