Skip to content

Instantly share code, notes, and snippets.

@rmosolgo
Created January 31, 2024 18:43
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/11983bad8e4b942f020bd1e046899191 to your computer and use it in GitHub Desktop.
Save rmosolgo/11983bad8e4b942f020bd1e046899191 to your computer and use it in GitHub Desktop.
Validate using one GraphQL schema, but execute using another schema
require "bundler/inline"
gemfile do
gem "graphql", "2.2.6"
end
class NewSchema < GraphQL::Schema
class Query < GraphQL::Schema::Object
field :old_field, Integer
def old_field = 1
field :new_field, Integer
def new_field = 2
end
query(Query)
end
OldSchema = GraphQL::Schema.from_definition <<-SCHEMA
type Query {
oldField: Int
}
SCHEMA
def run_as_if_old_schema(query_str)
# IRL this would be in your controller, for example
validation_errs = OldSchema.validate(query_str)
if validation_errs.any?
{
errors: validation_errs.map(&:to_h)
}
else
NewSchema.execute(query_str, validate: false)
end
end
pp run_as_if_old_schema("{ oldField }").to_h
# {"data"=>{"oldField"=>1}}
pp run_as_if_old_schema("{ newField }").to_h
# {:errors=>
# [{"message"=>"Field 'newField' doesn't exist on type 'Query'",
# "locations"=>[{"line"=>1, "column"=>3}],
# "path"=>["query", "newField"],
# "extensions"=>{"code"=>"undefinedField", "typeName"=>"Query", "fieldName"=>"newField"}}]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment