Skip to content

Instantly share code, notes, and snippets.

@ngw
Created August 14, 2018 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ngw/1aded5ecbf2dd38be0e2c9354a5a1253 to your computer and use it in GitHub Desktop.
Save ngw/1aded5ecbf2dd38be0e2c9354a5a1253 to your computer and use it in GitHub Desktop.
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,
}
result = DirectorySchema.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
private
# Handle form data, JSON body, or a blank value
def ensure_hash(ambiguous_param)
case ambiguous_param
when String
if ambiguous_param.present?
ensure_hash(JSON.parse(ambiguous_param))
else
{}
end
when Hash, ActionController::Parameters
ambiguous_param
when nil
{}
else
raise ArgumentError, "Unexpected parameter: #{ambiguous_param}"
end
end
def handle_error_in_development(e)
logger.error e.message
logger.error e.backtrace.join("\n")
render json: { error: { message: e.message, backtrace: e.backtrace }, data: {} }, status: 500
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment