Say I have the following json data:
"data": {
"continents": [
{
"code": "AF",
"name": "Africa",
},
{
"code": "EU",
"name": "Europe"
},
// ...
]
}
What would be the correct GraphQL query to fetch a list item with: code : "AF"
? In other words, how to produce the following result:
"data": {
"code": "AF",
"name": "Africa"
}
So far, I have:
query {
continents {
code
name
}
}
but that simply returns the full array.
I've been running my examples on: https://lucasconstantino.github.io/graphiql-online/
As it turns out, there is no built-in filter
function defined on lists/arrays! GraphQL (query language) is basically about selecting fields on objects [Schemas and Types | GraphQL].
One only needs to look at the GraphQL schema in question:
type Query {
continents(filter: ContinentFilterInput): [Continent!]!
// ...
}
type Continent {
code: ID!
name: String!
countries: [Country!]!
}
input ContinentFilterInput {
code: StringQueryOperatorInput
}
input StringQueryOperatorInput {
eq: String
ne: String
in: [String]
nin: [String]
regex: String
glob: String
}
// ...
We see that query continents
has a parameter filter
of input type ContinentFilterInput
. That's enough information for us to start building our filter query:
query {
continents(filter: ...) {
code
name
}
}
Upon inspecting ContinentFilterInput
, we observe that it has a single field code
of input type StringQueryOperatorInput
:
query {
continents(filter: { code: ...}) {
code
name
}
}
Finally, we find a field eq
inside input type StringQueryOperatorInput
which is a scalar type (String
) and we are done:
query {
continents(filter: { code: { eq: "AF" } }) {
code
name
}
}
For this current example you can just do
query {
continents(filter: {code: {eq: "AF"}}) {
name
}
}
I'd suggest to review the documentation regarding arguments since they explain it quite well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With