Handle multiple kind of requests in GraphQL controller

* Added support for GET requests
* Added support for application/graphql content-type for POST requests
* Handling query string parsing errors in controller
* Wrote specs for all this
This commit is contained in:
Alberto Miedes Garcés
2016-12-03 13:36:14 +01:00
parent a0f1976c1a
commit 6013f84945
3 changed files with 59 additions and 78 deletions

View File

@@ -4,11 +4,25 @@ class GraphqlController < ApplicationController
skip_authorization_check
def query
# ConsulSchema.execute returns the query result in the shape of a Hash, which
# is sent back to the client rendered in JSON
render json: ConsulSchema.execute(
params[:query],
variables: params[:variables] || {}
)
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?
render json: { message: 'Query string not present' }, status: :bad_request
else
begin
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