Table of Contents
Last updated
January 9, 2019
GraphQL Queries
Add type, query and schema for graphql
Now we need to add a type for Speaker, also a query and a schema for GraphQL.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'graphql' | |
require_relative 'base_object' | |
class Types::Speaker < Types::BaseObject | |
description 'Resembles a Speaker Object Type' | |
field :id, ID, null: false | |
field :name, String, null: false | |
field :twitter_handle, String, null: true | |
field :bio, String, null: true | |
field :talk_title, String, null: true | |
end |
We need to then add a root query in query.rb
file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'graphql' | |
require_relative 'types/speaker' | |
class QueryType < GraphQL::Schema::Object | |
description "The query root of this schema" | |
field :speakers, [Types::Speaker], null: false do | |
description 'Get all speakers of the system' | |
end | |
def speakers | |
Speaker.all | |
end | |
end |
And include the query in the schema.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'graphql' | |
require_relative 'query' | |
class ConferenceAppSchema < GraphQL::Schema | |
query QueryType | |
end |
Querying the endpoint
You can use the GraphiQL app or the Postman app to query the endpoint. Make sure that you have puma running and the server is up.
A JSON response like the below will be obtained.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"data": { | |
"speakers": [ | |
{ | |
"name": "John", | |
"twitterHandle": "johnruby", | |
"bio": "This is John's bio" | |
}, | |
{ | |
"name": "Jacob", | |
"twitterHandle": "jacob-ruby", | |
"bio": "This is Jacob\\'s bio" | |
} | |
] | |
} | |
} |
Now you have a GraphQL server up and running on sinatra, and you can query the endpoint to get a list of speakers with the fields defined in the GraphQL query.
In the next part we will add mutations.
…