Refactor GraphqlController
This commit is contained in:
@@ -1,28 +1,44 @@
|
|||||||
class GraphqlController < ApplicationController
|
class GraphqlController < ApplicationController
|
||||||
|
attr_accessor :query_variables, :query_string
|
||||||
|
|
||||||
skip_before_action :verify_authenticity_token
|
skip_before_action :verify_authenticity_token
|
||||||
skip_authorization_check
|
skip_authorization_check
|
||||||
|
|
||||||
|
class QueryStringError < StandardError; end
|
||||||
|
|
||||||
def query
|
def query
|
||||||
|
begin
|
||||||
if request.headers["CONTENT_TYPE"] == 'application/graphql'
|
set_query_environment
|
||||||
query_string = request.body.string # request.body.class => StringIO
|
response = ConsulSchema.execute query_string, variables: query_variables
|
||||||
else
|
render json: response, status: :ok
|
||||||
query_string = params[:query]
|
rescue GraphqlController::QueryStringError
|
||||||
end
|
|
||||||
|
|
||||||
if query_string.nil?
|
|
||||||
render json: { message: 'Query string not present' }, status: :bad_request
|
render json: { message: 'Query string not present' }, status: :bad_request
|
||||||
else
|
rescue GraphQL::ParseError
|
||||||
begin
|
render json: { message: 'Query string is not valid JSON' }, status: :bad_request
|
||||||
response = ConsulSchema.execute(
|
|
||||||
query_string,
|
|
||||||
variables: params[:variables] || {}
|
|
||||||
)
|
|
||||||
render json: response, status: :ok
|
|
||||||
rescue GraphQL::ParseError
|
|
||||||
render json: { message: 'Query string is not valid JSON' }, status: :bad_request
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def set_query_environment
|
||||||
|
set_query_string
|
||||||
|
set_query_variables
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_query_string
|
||||||
|
if request.headers["CONTENT_TYPE"] == 'application/graphql'
|
||||||
|
@query_string = request.body.string # request.body.class => StringIO
|
||||||
|
else
|
||||||
|
@query_string = params[:query]
|
||||||
|
end
|
||||||
|
if query_string.nil? then raise GraphqlController::QueryStringError end
|
||||||
|
end
|
||||||
|
|
||||||
|
def set_query_variables
|
||||||
|
if params[:variables].nil?
|
||||||
|
@query_variables = {}
|
||||||
|
else
|
||||||
|
@query_variables = params[:variables]
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user