Table of Contents
Last updated
January 9, 2019
Setting up GraphQL
Now we have a sinatra app that connects to the database and shows a list of speakers as a JSON response. Now let’s add graphql and define a schema for speakers.
Add the graphql
gem. https://github.com/rmosolgo/graphql-ruby.
Also the rack-contrib
gem needs to be added so that the sinatra app can accept raw JSON payloads.
GraphQL works on a “schema” (basically something like a database schema), with the required models that needs to be queried or updated. So we need to define a schema.
This file contains hidden or 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 |
The /graphql
endpoint
We now need to have a POST endpoint for GraphQL.
GraphQL schema can be executed to give a GraphQL::Query::Result
which can then be converted to JSON. app.rb
needs change to include this endpoint.
This file contains hidden or 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
# Changes to file app.rb | |
# ... | |
require 'rack/contrib' | |
class ConferenceApp < Sinatra::Base | |
# ... | |
use Rack::PostBodyContentTypeParser | |
# ... | |
# ... | |
post '/graphql' do | |
result = ConferenceAppSchema.execute( | |
params[:query], | |
variables: params[:variables], | |
context: { current_user: nil }, | |
) | |
json result | |
end | |
# ... | |
end |
…