Objects
type User {
id
name
}
Objects are the principal type of GraphQL. In contrast with Scalars, objects create branches in the GraphQL tree. It is always through them that you will be able to organize and access your data.
Creating an Object
You can define objects on a file or using the shortcut on the schema.
# app/graphql/objects/user.rb
module GraphQL
class User < GraphQL::Object
field :id
field :name
end
end
# OR
# app/graphql/app_schema.rb
object 'User' do
field :id
field :name
end
Read more about field lists.
Description
Allows documenting objects. This value can be retrieved using introspection
or during a to_gql output. Within the class, desc
works as a syntax sugar for self.description = ''
. It also supports descriptions from
I18n.
# app/graphql/objects/user.rb
module GraphQL
class User < GraphQL::Object
desc 'This is awesome!'
end
end
Implementing Interfaces
Objects can implement interfaces, meaning they will receive a series of imported fields or comply with what is configured in the interface.
# app/graphql/objects/user.rb
implements 'Person'
Read more about interfaces.
For gem Creators
Once you have created your objects in your gem, remember to add them into
config.known_dependencies
.
It is not recommended to require
such files in your gem.
Rails::GraphQL.config.known_dependencies[:object].update(
my_gem_object: "#{__dir__}/objects/my_gem_object",
)
Using Objects
Once they are defined, you can set them as the type of output fields. Then, in your execution document, you can use query any of the fields that were defined.
field(:recipient, 'User')
{ recipient { id name } }
Objects is the best place for you to set up your Models.