Last active
January 18, 2025 15:36
-
-
Save rmosolgo/ae3e28bedf3866677bd05cd7bf945bc5 to your computer and use it in GitHub Desktop.
Custom GraphQL-Ruby Schema Printer Which Doesn't Sort Enum Values
This file contains 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.4.8" | |
end | |
class MySchema < GraphQL::Schema | |
class Vegetable < GraphQL::Schema::Enum | |
value :ZUCCHINI | |
value :ARTICHOKE | |
value :CUCUMBER | |
value :JICAMA | |
value :BANANA_PEPPER | |
end | |
class Query < GraphQL::Schema::Object | |
field :vegetable, Vegetable | |
end | |
query(Query) | |
end | |
pp MySchema.execute('{ __type(name: "Vegetable") { enumValues { name } } }').to_h | |
# {"data" => | |
# {"__type" => | |
# {"enumValues" => | |
# [{"name" => "ZUCCHINI"}, | |
# {"name" => "ARTICHOKE"}, | |
# {"name" => "CUCUMBER"}, | |
# {"name" => "JICAMA"}, | |
# {"name" => "BANANA_PEPPER"}]}}} | |
puts MySchema.to_definition | |
# type Query { | |
# vegetable: Vegetable | |
# } | |
# enum Vegetable { | |
# ARTICHOKE | |
# BANANA_PEPPER | |
# CUCUMBER | |
# JICAMA | |
# ZUCCHINI | |
# } | |
puts "\n~~~~~~~~~~~~~~~~~~\n" | |
class CustomDocumentFromSchemaDefinition < GraphQL::Language::DocumentFromSchemaDefinition | |
# Override this based on DocumentFromSchemaDefinition#build_enum_type_node to _not_ sort the values | |
def build_enum_type_node(enum_type) | |
GraphQL::Language::Nodes::EnumTypeDefinition.new( | |
name: enum_type.graphql_name, | |
comment: enum_type.comment, | |
# No sort-by call here: | |
values: @types.enum_values(enum_type).map do |enum_value| | |
build_enum_value_node(enum_value) | |
end, | |
description: enum_type.description, | |
directives: directives(enum_type), | |
) | |
end | |
end | |
class CustomSchemaPrinter < GraphQL::Schema::Printer | |
# Override this to use `CustomDocumentFromSchemaDefinition` | |
def initialize(schema, context: nil, introspection: false) | |
@document_from_schema = CustomDocumentFromSchemaDefinition.new( | |
schema, | |
context: context, | |
include_introspection_types: introspection, | |
) | |
@document = @document_from_schema.document | |
@schema = schema | |
end | |
end | |
puts CustomSchemaPrinter.print_schema(MySchema) | |
# type Query { | |
# vegetable: Vegetable | |
# } | |
# enum Vegetable { | |
# ZUCCHINI | |
# ARTICHOKE | |
# CUCUMBER | |
# JICAMA | |
# BANANA_PEPPER | |
# } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment