How to get all user model with GraphQL

1.5k Views Asked by At

I have been struggling with this for over an hour, but can't seem to get it to work.

I'm using the ruby implementation of GraphQL together with Rails and i'm trying to do a User.all with GraphQL. I have the following QueryType which defines the field users.

QueryType = GraphQL::ObjectType.define do
  name "Query"
  description "The query root for this schema"

  field :users do
    types[IndexUserType]

    resolve -> () {
      User.all
    }
  end
end

and the IndexUserType defined as follows:

IndexUserType = GraphQL::ObjectType.define do
  name "IndexUserType"
  description "An Index User"
  field :firstname, types.String
end

and i'm trying to get all the users with their firstname using the following query:

query={ users { firstname } }

Normally I could to the following on Has-Many relationships, however this is not working and I think this is because the 'obj' cannot be set without a parent.

resolve -> (obj, args, ctx) {
  obj.cousins
}
2

There are 2 best solutions below

0
On BEST ANSWER

After a lot of trial and error, I managed to solve a get all with the following:

field :users, types[IndexUserType] do
  resolve -> (obj, args, ctx) {
    User.all
  }
end
0
On

In your original solution, you defined the attributes of the field in the block, when you do that you need to declare the type by doing:

field :users do
    type types[IndexUserType] # <-- Note the addition of 'type'
    ...
end

Your second solution passes the same information in the argument list to 'field' which also works. This is supported via the InstanceDefinable mixin. You might want to take a look at the documentation for GraphQL::Field to see additional examples of how fields can be defined. If you want to dig a bit deeper, take a look at GraphQL::Define::InstanceDefinable which can help you understand how this pattern is used in Field and other classes in the graphql-ruby gem.

See:

http://www.rubydoc.info/github/rmosolgo/graphql-ruby/GraphQL/Field http://www.rubydoc.info/github/rmosolgo/graphql-ruby/GraphQL/Define/InstanceDefinable