Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Created January 11, 2024 14:57
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 rmosolgo/9d4ab65e2a4c2ad379eb3bf7b03f17d5 to your computer and use it in GitHub Desktop.
Save rmosolgo/9d4ab65e2a4c2ad379eb3bf7b03f17d5 to your computer and use it in GitHub Desktop.
GraphQL-Ruby 1.12 field deprecation warnings example
require "bundler/inline"
gemfile do
gem "graphql", "1.12.24"
end
# Newer graphql-ruby versions have `context.repsonse_extensions` which automatically
# adds data to the result["extensions"] field. But for 1.12, you have to add it manually.
# @see https://graphql-ruby.org/queries/response_extensions.html
class MySchema < GraphQL::Schema
class DeprecatedFields < GraphQL::Analysis::AST::FieldUsage
def result
field_usage = super
if field_usage[:used_deprecated_fields].any?
# Store the warnings here for now:
query.context[:deprecation_warnings] = field_usage[:used_deprecated_fields].map do |field_path|
field_defn = MySchema.get_field(*field_path.split("."))
{
"field" => field_path,
"deprecationReason" => field_defn.deprecation_reason,
}
end
end
end
end
class Query < GraphQL::Schema::Object
field :field1, Int, null: false
field :field2, Int, null: false, deprecation_reason: "Irrelevant"
end
query_analyzer(DeprecatedFields)
query(Query)
end
result = MySchema.execute("{ field1 field2 }", root_value: { field1: 1, field2: 2 })
# Now, add the warnings to the response:
if (warnings = result.context[:deprecation_warnings])
result["extensions"] = {
"deprecationWarnings" => warnings
}
end
pp result.to_h
# {
# "data" => {
# "field1" => 1,
# "field2" => 2
# },
# "extensions" => {
# "deprecationWarnings" => [
# {
# "field" => "Query.field2",
# "deprecationReason" => "Irrelevant"
# }
# ]
# }
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment