Returning an array graphQL

1.4k views Asked by At

I'm currently trying to learn GraphQL but running into a problem. The problem is possibly not understanding the right way in writing my types. When I had my user type as

module Types
  UserType = GraphQL::ObjectType.define do
    name 'User'

    field :id, !types.ID
    field :username, !types.String
    field :email, !types.String, property: :email_address
    field :workspaces, types[Types::WorkspaceType]
  end
end

I'm able to return an array of workspaces without a problem. Now the problem comes when I try to return an array of users that are associated with that workspace. My workspace type looks like this

class Types::WorkspaceType < Types::BaseObject
  field :id, ID, null: false
  field :user_id, ID, null: false
  field :name, String, null: false
  field :members, types[Types::UserType]
end

When I try to run the query in fetching the workspace I'm getting an error that says

  "error": {
    "message": "undefined local variable or method `types' for Types::UserType:Class",

The backend I'm using is Ruby on Rails. For those with some experience with GraphQL, I would love feedback in what I'm doing wrong and also what is the right way in connecting types between each model. If there are any extra information you'll need or want clarification with please feel free to ask.

Thank you.

1

There are 1 answers

0
David Maze On

The graphql gem has two different "styles" of declaring GraphQL objects using a Ruby DSL (and it can also directly import the GraphQL schema language). The older style (now expunged from the docs) uses GraphQL::ObjectType.define, and needs to qualify most references with the types syntax. The newer style uses Ruby class inheritance, and doesn't use types.

In short: I think your code will work if you just change the last field definition to

field :members, [Types::UserType]