Created
January 20, 2020 08:14
-
-
Save DmitryTsepelev/17a495af2fcdc7d2835c8d38df492626 to your computer and use it in GitHub Desktop.
ruby-graphql + HTTP GET
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class GraphqlSchema < GraphQL::Schema | |
query_analyzer Analyzers::HttpMethodAnalyzer.new | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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