Sha256: 3f9bcf4d69ed456dc7bd83c91f77087a91949ed88fe9f0b2328456eafc03bc67

Contents?: true

Size: 1.37 KB

Versions: 2

Compression:

Stored size: 1.37 KB

Contents

module GraphQLPreview
  # Modify each field & argument in the schema so that
  # its metadata contains the preview, if there is one.
  class Instrumenter
    def initialize(enabled_previews, possible_environments)
      @enabled_previews = enabled_previews
      @possible_environments = possible_environments
    end

    def instrument(type, field)
      # Maybe get an isolated copy that we can modify
      field_dup = nil

      if (preview = enabled_previews.find { |prev| prev.toggled_on.include?("#{type.name}.#{field.name}")})
        field_dup = field.dup
        assign_preview(field_dup, preview)
      end

      # Return the modified copy if we made one,
      # otherwise return the original
      field_dup || field
    end

    private

    attr_reader :enabled_previews

    def assign_preview(obj, preview)
      if obj.metadata[:preview_toggled_by]
        raise ArgumentError, "Couldn't add `#{preview}` to `#{obj.name}`: it's already toggled with `#{obj.metadata[:preview_toggled_by].toggled_by}`"
      end

      environments = if preview.environments
        preview.environments
      else
        @possible_environments
      end

      value = Hash[environments.map{ |env| [env, preview] }]

      obj.metadata[:preview_toggled_by] = value

      if obj.respond_to?(:mutation) && (mut = obj.mutation)
        mut.metadata[:preview_toggled_by] = value
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
graphql-preview-0.2.0 lib/graphql-preview/instrumenter.rb
graphql-preview-0.1.1 lib/graphql-preview/instrumenter.rb