Files
grecia/app/controllers/graphql_controller.rb
Javi Martín 6fd9a286d7 Don't access the database in after_initialize
Rails 5.2 crashes in the `db:create` task because it tries to run the
`after_initialize` block before the database is created.

The easiest way to solve it is to move the code out of the initializer
and calculate the API type definitions on demand. Note results are still
cached using a class instance variable (not to be confused with a class
variable), and so once definitions are obtained, they will remain
constant until the application is restarted, even in the development
environment.
2020-07-08 18:34:58 +02:00

58 lines
1.5 KiB
Ruby

class GraphqlController < ApplicationController
include FeatureFlags
feature_flag :graphql_api
skip_before_action :verify_authenticity_token
skip_authorization_check
class QueryStringError < StandardError
end
def query
begin
if query_string.nil? then raise GraphqlController::QueryStringError end
response = consul_schema.execute query_string, variables: query_variables
render json: response, status: :ok
rescue GraphqlController::QueryStringError
render json: { message: "Query string not present" }, status: :bad_request
rescue JSON::ParserError
render json: { message: "Error parsing JSON" }, status: :bad_request
rescue GraphQL::ParseError
render json: { message: "Query string is not valid JSON" }, status: :bad_request
rescue
unless Rails.env.production? then raise end
end
end
private
def consul_schema
api_types = GraphQL::ApiTypesCreator.create
query_type = GraphQL::QueryTypeCreator.create(api_types)
GraphQL::Schema.define do
query query_type
max_depth 8
max_complexity 2500
end
end
def query_string
if request.headers["CONTENT_TYPE"] == "application/graphql"
request.body.string # request.body.class => StringIO
else
params[:query]
end
end
def query_variables
if params[:variables].blank? || params[:variables] == "null"
{}
else
JSON.parse(params[:variables])
end
end
end