Search code examples
jsongraphqlgraphql-js

GraphQL filter data by key values (e.g. users age must be 31)


I'm new to GraphQL and I'm stuck on a rather simple problem which I've yet to find documentation for.

The only thing I'm trying to do is get a list of users from a JSON that have their age key set to 31. I can easily get all the users by doing:

{
  user {
    name
    age
  }
}

But I only want users that are aged 31 and what I think I need to do, which doesn't work, is:

{
  user(age: 31) {
    name
    age
  }
}

I just get the same results, so what do I need to do to enable the age: 31 "filter"?

Schema

var MyGraphQLSchema = buildSchema(`
  type Query {
    user(age: Int): [User]
  }
  type User {
    id: Int
    name: String
    age: Int
  }
`);

JSON Data

var root = {
  "user": [
    {
      "id": 1,
      "name": "binni",
      "age": 31
    },
    {
      "id": 2,
      "name": "viddi",
      "age": 31
    },
    {
      "id": 3,
      "name": "mási",
      "age": 32
    }
  ]
}

GraphQL Server

graphqlHTTP({
  schema: MyGraphQLSchema,
  rootValue: root,
  graphiql: true
})

I'm using graphql.js and koa-graphql (which is similiar to express-graphql).

Query Results

{
  "data": {
    "user": [
      {
        "name": "binni",
        "age": 31
      },
      {
        "name": "viddi",
        "age": 31
      },
      {
        "name": "mási",
        "age": 32
      }
    ]
  }
}

Solution

  • You need to implement user as an ECMAScript function, instead of as an array.

    var users = [
          {
            "name": "binni",
            "age": 31
          },
          {
            "name": "viddi",
            "age": 31
          },
          {
            "name": "mási",
            "age": 32
          }
        ]
    
    
    var root = {
      "user": ({age}) =>
                age === null? users:
                              users.filter(user => user.age === age)
    }
    

    See http://graphql.org/graphql-js/passing-arguments/ for reference.