Last active
November 10, 2019 09:34
-
-
Save harigopal/877e2d5c9f79c1c1887e8ee9538d1bdd to your computer and use it in GitHub Desktop.
Conventions for setting up a GraphQL Server on Rails - Routes & controllers
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
# 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