I'm working on a GraphQL API in Rails. I want to know if queries can have multiple return types.
For instance, I want to return a integer count of people in the lobby. Then, I want to return their associated UserTypes.
{ "users": [Types::UserType], "user_count": Integer
Here's the query:
module Queries
class FetchLobbyCount < Queries::BaseQuery
graphql_name "FetchLobbyCount"
argument :user_id, Integer, required: false
type Integer, null: false
def resolve(user_id:)
@user = User.find(user_id)
unless @user.present?
return GraphQL::ExecutionError.new("Cannot find user with id: #{user_id}")
end
User.where(awaiting_match: true).where.not(id: user_id).count
end
end
end
I've tried using the field
keyword to define the return types.
The way you return more data is to define a Type that contains the fields you want to return eg:
module Queries
class FetchLobbyCount < Queries::BaseQuery
graphql_name "FetchLobbyCount"
argument :user_id, Integer, required: false
type LobbyUsersType, null: false
def resolve(user_id:)
@user = User.find(user_id)
unless @user.present?
return GraphQL::ExecutionError.new("Cannot find user with id: #{user_id}")
end
User.where(awaiting_match: true).where.not(id: user_id).count
end
end
end
and then something like:
module Types
class LobbyUsersType
description 'Information about users in a given lobby'
field :lobby_id, Integer, "ID of the lobby we're fetching the users for", null: true
field :user_count, Integer, "Number of users in this lobby", null: true
# etc...
end
end