In order to be able to show all links, you first need to set up your database so the links can be stored.
This generates a
link.rb file in
app/models that will look as follows:
class Link < ApplicationRecord end
This is our
Awesome! You now have a database table to store the links and a few dummy records setup.
Now, go ahead and define your GraphQL Type for links. GraphQL Ruby uses a DSL for that.
This creates the file
app/graphql/types/link_type.rb with the following content:
module Types class LinkType < BaseObject field :id, ID, null: false field :url, String, null: false field :description, String, null: false end end
The type is now defined, but the server still doesn’t know how to handle it. To fix that, you will now write your first resolver. Resolvers are functions that the GraphQL server uses to fetch the data for a specific query. Each field of your GraphQL types needs a corresponding resolver function. When a query arrives at the backend, the server will call those resolver functions that correspond to the fields that are specified in the query.
All GraphQL queries start from a root type called Query.
When you previously ran
rails generate graphql:install, it created the root query type in
app/graphql/types/query_type.rb for you.
Fields can be resolved in one of two ways:
It’s time to check what you’ve done so far! For this, you’ll use GraphiQL, an in-browser IDE for running GraphQL queries.
GraphiQL had already been added to your application when you executed
rails generate graphql:install in the terminal before, but you have to tell the asset pipeline to precompile its assets. Add this at the end of
//= link graphiql/rails/application.css //= link graphiql/rails/application.js
Open your browser at http://localhost:3000/graphiql
You’ll see a nice IDE that looks like this:
Click on the Docs link at the upper right to see a generated documentation of your schema. You’ll see the
Query type there, and clicking it will show you the new
allLinks field, exactly as you’ve defined it. The documentation in GraphiQL is generated automatically based on your schema. This works thanks to a mechanism called Introspection.
Try it out! On the left-most text box, type a simple query for listing all links and hit the Play button. This is what you’ll see:
You can play around as much as you want with this tool. It makes testing GraphQL APIs so fun and easy, you’ll never want to live without it any more. 😎
Learn best practices for implementing GraphQL mutations with Ruby and graphql-ruby. You can test your implementation in a GraphiQL Playground.