Skip to content

Instantly share code, notes, and snippets.

@harigopal
Last active November 10, 2019 09:34
Show Gist options
  • Save harigopal/877e2d5c9f79c1c1887e8ee9538d1bdd to your computer and use it in GitHub Desktop.
Save harigopal/877e2d5c9f79c1c1887e8ee9538d1bdd to your computer and use it in GitHub Desktop.
Conventions for setting up a GraphQL Server on Rails - Routes & controllers
# config/routes.rb
if Rails.env.development?
mount GraphiQL::Rails::Engine, at: "/graphiql", graphql_path: "/graphql"
end
post "/graphql", to: "graphql#execute"
# app/controllers/graphql_controller.rb
class GraphqlController < ApplicationController
def execute
variables = ensure_hash(params[:variables])
query = params[:query]
operation_name = params[:operationName]
context = {
# Query context goes here, for example:
# current_user: current_user,
}
# This is the interesting part. Notice how the schema class is being asked to execute the incoming query.
result = MyRailsAppSchema.execute(query, variables: variables, context: context, operation_name: operation_name)
render json: result
rescue => e
raise e unless Rails.env.development?
handle_error_in_development e
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment