Skip to content

Instantly share code, notes, and snippets.

@DmitryTsepelev
Created January 20, 2020 08:14
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 DmitryTsepelev/17a495af2fcdc7d2835c8d38df492626 to your computer and use it in GitHub Desktop.
Save DmitryTsepelev/17a495af2fcdc7d2835c8d38df492626 to your computer and use it in GitHub Desktop.
ruby-graphql + HTTP GET
class GraphqlController < ApplicationController
include EnsureHash
def execute
result = GraphqlSchema.execute(
params[:query],
variables: ensure_hash(params[:variables]),
context: context,
operation_name: params[:operationName],
)
render json: result
end
private
def context
@context ||= {
request: request,
}
end
end
class GraphqlSchema < GraphQL::Schema
query_analyzer Analyzers::HttpMethodAnalyzer.new
end
class HttpMethodAnalyzer
def analyze?(query)
!!query.context[:request]
end
def initial_value(query)
{
get_request: query.context[:request].get?,
mutation: query.mutation?,
}
end
def call(memo, _visit_type, _irep_node)
memo
end
def final_value(memo)
return if !memo[:get_request] || !memo[:mutation]
GraphQL::AnalysisError.new("Mutations cannot be performed via HTTP GET")
end
end
require "sidekiq/web"
require "sidekiq/grouping/web"
require "sidekiq-scheduler/web"
Rails.application.routes.draw do
get "/graphql", to: "graphql#execute"
post "/graphql", to: "graphql#execute"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment