Step 2: Your First Type - aaronpanch/idea-board GitHub Wiki
After asking the right questions, hopefully you've decided we need to expose some data. Specifically, some non-scalar or "object" types. Let's do that here.
As the header suggests, we're going to create a type for our idea objects. I've created a directory for this named: app/graphql/idea_board_graphql/types
.
So, the first thing we need to do is create a file in that directory called: idea.rb
where we will define our Idea Object Type. Paste the following code in:
module IdeaBoardGraphql
module Types
class Idea < GraphQL::Schema::Object
end
end
end
Great—we've got a type! The modules correspond to how we've namespaced things, but the key thing to note is that our Idea type inherits from GraphQL::Schema::Object
, which is the base object type.
That's all fine and dandy, but we need to expose some fields! Remember a tip (from a past talk): we don't need to expose everything. So lets start by just exposing the Idea's id
:
module IdeaBoardGraphql
module Types
class Idea < GraphQL::Schema::Object
field :id, GraphQL::Types::ID, null: false,
description: "The idea's unique identifier."
end
end
end
Next, lets add a resolver for id
:
module IdeaBoardGraphql
module Types
class Idea < GraphQL::Schema::Object
field :id, GraphQL::Types::ID, null: false,
description: "The idea's unique identifier."
def id
object.id
end
end
end
end
Great! Some things to note:
-
object
: when resolving an object type, we need access to the "object" that we're "unpacking". In this case, a parent resolver (probably the root) is going to fetch an idea from the DB, and use this type to resolve various fields on an Idea model instance. GraphQL Ruby sets up this data object usingobject
.
Now, hopefully someone is thinking "there's gotta be a better way"—and yes, there is! We can just get by with:
module IdeaBoardGraphql
module Types
class Idea < GraphQL::Schema::Object
field :id, GraphQL::Types::ID, null: false,
description: "The idea's unique identifier."
end
end
end
Why? Well, we're relying on the notion of default resolvers. So, when GQL is resolving a Types::Idea
it will call the method of the same name as the field on the underlying object
, so we're done!
I suggest we get things running in the playground next, so let's do that. It's up to you to:
-
Expose a query to allow users to ask for all ideas. Remember our ping/pong example?
Expand for a hint
Add a field called `ideas` on the root query type. -
We need to tell GraphQL that the returned type for the query is our newly defined custom type as a list.
Expand for a hint
See this link for documentation advice: https://graphql-ruby.org/fields/introduction.html#field-return-type
Expand for a partial answer
[Types::Idea]
Expand for the full answer (please try first!)
field :ideas, [Types::Idea], null: false
-
Give it a go in the playground!
Expand for how to query
query Ideas { ideas { id } }
-
Expose the
title
field