Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Created April 18, 2019 16:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmosolgo/c0f77ec8bde255daab4cc8122a8226dc to your computer and use it in GitHub Desktop.
Save rmosolgo/c0f77ec8bde255daab4cc8122a8226dc to your computer and use it in GitHub Desktop.
Accessing directives in the Schema SDL with GraphQL-Ruby
require "graphql"
# A schema definition with field-level directives
schema = GraphQL::Schema.from_definition <<-GRAPHQL
type Query {
totalScore: Int! @mock
}
type Mutation {
incrementScore(by: Int = 1): Int! @mock(with: "SomeClassName")
}
GRAPHQL
# Accessing the directive names
total_score_field = schema.types["Query"].fields["totalScore"]
directive_nodes = total_score_field.ast_node.directives
p directive_nodes.map(&:name)
# ["mock"]
# An example accessing the arguments of a directive
increment_score_field = schema.types["Mutation"].fields["incrementScore"]
directive_nodes = increment_score_field.ast_node.directives
directive_nodes.each do |dir|
args = dir.arguments.map { |a| "#{a.name} => #{a.value}" }
puts "#{dir.name}(#{args.join(",")})"
# mock(with => SomeClassName)
end
@JuanitoFatas
Copy link

@rmosolgo thanks for this. Is it possible to output each type’s SDL from an existing Ruby schema?

@rmosolgo
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment