Sha256: ef5adfe42fa96ad82522d14bad83bdd422f20b063ebdee5c829aa466e9e667a2

Contents?: true

Size: 1.16 KB

Versions: 4

Compression:

Stored size: 1.16 KB

Contents

class GraphQL::StaticValidation::FragmentsAreUsed
  include GraphQL::StaticValidation::Message::MessageHelper

  def validate(context)
    v = context.visitor
    used_fragments = []
    defined_fragments = []
    v[GraphQL::Nodes::FragmentSpread] << -> (node, parent) { used_fragments <<  node }
    v[GraphQL::Nodes::FragmentDefinition] << -> (node, parent) { defined_fragments << node}
    v[GraphQL::Nodes::Document].leave << -> (node, parent) { add_errors(context.errors, used_fragments, defined_fragments) }
  end

  private

  def add_errors(errors, used_fragments, defined_fragments)
    undefined_fragments = find_difference(used_fragments, defined_fragments.map(&:name))
    undefined_fragments.each do |fragment|
      errors << message("Fragment #{fragment.name} was used, but not defined", fragment)
    end

    unused_fragments = find_difference(defined_fragments, used_fragments.map(&:name))
    unused_fragments.each do |fragment|
      errors << message("Fragment #{fragment.name} was defined, but not used", fragment)
    end
  end

  def find_difference(fragments, allowed_fragment_names)
    fragments.select {|f| !allowed_fragment_names.include?(f.name) }
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
graphql-0.5.0 lib/graph_ql/static_validation/rules/fragments_are_used.rb
graphql-0.4.0 lib/graph_ql/static_validation/rules/fragments_are_used.rb
graphql-0.3.0 lib/graph_ql/static_validation/rules/fragments_are_used.rb
graphql-0.2.0 lib/graph_ql/static_validation/fragments_are_used.rb