Created
May 21, 2025 19:16
-
-
Save rmosolgo/9d139454c50678cc23ec792402844d75 to your computer and use it in GitHub Desktop.
Log GraphQL-Ruby arguments in their GraphQL format
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 "bundler/inline" | |
gemfile do | |
gem "graphql", "2.5.6" | |
gem "uri" | |
end | |
class MySchema < GraphQL::Schema | |
class Uri < GraphQL::Schema::Scalar | |
def self.coerce_input(value, ctx) | |
URI.parse(value) | |
end | |
end | |
class ComplexInput < GraphQL::Schema::InputObject | |
argument :id, ID | |
argument :float, Float | |
argument :uniform_resource_locator, Uri | |
end | |
class Query < GraphQL::Schema::Object | |
field :get_stuff, String, extras: [:ast_node] do | |
argument :strs, [String] | |
argument :obj, ComplexInput | |
end | |
def get_stuff(strs:, obj:, ast_node:) | |
log_arguments(context, ast_node) | |
"OK" | |
end | |
end | |
query(Query) | |
end | |
def log_arguments(context, ast_node) | |
formatted_args = {} | |
ast_node.arguments.each do |argument_node| | |
formatted_args[argument_node.name] = format_argument(context, argument_node.value) | |
end | |
puts "ARGUMENTS:" | |
pp formatted_args | |
end | |
def format_argument(context, argument_value) | |
case argument_value | |
when String, Numeric | |
argument_value | |
when Array | |
argument_value.map { |v| format_argument(context, v) } | |
when GraphQL::Language::Nodes::InputObject | |
args = {} | |
argument_value.arguments.each do |arg_node| | |
args[arg_node.name] = format_argument(context, arg_node.value) | |
end | |
args | |
when GraphQL::Language::Nodes::VariableIdentifier | |
var_value = context.query.variables[argument_value.name] | |
formatted = format_argument(context, var_value) | |
# You could return one of these or both, depending on your needs: | |
{ | |
variable: "$" + argument_value.name, | |
runtime_value: formatted, | |
} | |
else | |
raise ArgumentError, "Unsupported argument value, implement a `when` clause for it: #{argument_value.class} (#{argument_value.class})" | |
end | |
end | |
pp MySchema.execute(<<~GRAPHQL, variables: { f: 5.67 }).to_h | |
query ArgTest($world: String = "World", $f: Float!) { | |
getStuff( | |
strs: ["Hello", $world], | |
obj: { id: 123, float: $f, uniformResourceLocator: \"https://graphql-ruby.org\"} | |
) | |
} | |
GRAPHQL | |
# ARGUMENTS: | |
# {"strs" => ["Hello", {variable: "$world", runtime_value: "World"}], | |
# "obj" => | |
# {"id" => 123, | |
# "float" => {variable: "$f", runtime_value: 5.67}, | |
# "uniformResourceLocator" => "https://graphql-ruby.org"}} | |
# | |
# {"data" => {"getStuff" => "OK"}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment