Sha256: 8e08399921b74c7fb67e01505516c77ff8d9a638c4233ac2cf83af910b275d31

Contents?: true

Size: 1.42 KB

Versions: 11

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

require 'graphql'

module PlatformosCheck
  class GraphqlTraverser
    def initialize(graphql_file)
      @graphql_file = graphql_file
    end

    def fields
      pickup_fields(@graphql_file.selections, '')
    end

    private

    def pickup_fields(selections, path = '')
      selections = expand_fragments(selections)
      fields = {}
      fields['/'] = map_names_from_selections(selections) if path.empty?
      selections.map do |selection|
        current_path = File.join(path, name_from_selection(selection))
        fields[current_path] = map_names_from_selections(expand_fragments(selection.selections))

        child_fields = pickup_fields(selection.selections, current_path)
        fields = fields.merge(child_fields)
      end
      fields
    end

    def map_names_from_selections(selections)
      selections.map { |selection| name_from_selection(selection) }
    end

    def name_from_selection(selection)
      selection.alias || selection.name
    end

    def expand_fragments(selections)
      selections.map do |selection|
        if selection.is_a?(GraphQL::Language::Nodes::FragmentSpread)
          find_fragment(selection.name).selections
        else
          selection
        end
      end.flatten.uniq { |s| name_from_selection(s) }
    end

    def find_fragment(fragment_name)
      @graphql_file.fragments.detect { |definition| definition.name == fragment_name }
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
platformos-check-0.4.14 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.13 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.12 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.11 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.10 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.9 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.8 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.7 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.6 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.5 lib/platformos_check/graphql_traverser.rb
platformos-check-0.4.4 lib/platformos_check/graphql_traverser.rb