0
votes

I am new to GraphQL. I know this is a basic question but hope someone could help me to add variables to my query as I tried many times and failed :(

In my query, below schema is used:

type Query {
    ContinentInfo(id: ID): Continent
}

type Continent {
  id  : ID
  name: String
  countries: [Country]
}

type Country {
  id        : ID
  name      : String
  population: Float
}

Below query is executed successfully:

{
    ContinentInfo(id: "continent01") {
        name
        countries {
            name
            population
        }
    }
}

Then I want to add more conditions in the query, for example add a variable "populationMoreThan" to filter the result. so the query may look like:

{
    ContinentInfo(id: "continent01") {
        name
        countries(populationMoreThan: $populationMoreThan) {
            name
            population
        }
    }
}

but it always failed when I tried to add this variable in the schema and in the query. Could anyone provide me an example of adding variable in my case? Also, it looks I need to pass the parameter value into the query? Now I'm using graphql.GraphQL.execute(queryString) to pass the query string. How to pass the variable value here?

1

1 Answers

0
votes

Finally found a way to filter the result. Update the schema with:

type Continent {
  id  : ID
  name: String
  countries(populationMoreThan: Float = 0): [Country]
}

And query with:

{
    ContinentInfo(id: "continent01") {
        name
        countries(populationMoreThan: 1.0) {
            name
            population
        }
    }
}