module KongSchema::Reporter

Helper class for printing a report of the changes to be committed to Kong created by {Schema.analyze}.

Constants

TableHeader

Public Instance Methods

report(changes, object_format: :json) click to toggle source

@param [Array<KongSchema::Action>] changes

What you get from calling {KongSchema::Schema.analyze}

@return [String] The report to print to something like STDOUT.

# File lib/kong_schema/reporter.rb, line 22
def report(changes, object_format: :json)
  pretty_print = if object_format == :json
    JSONPrettyPrinter.method(:print)
  else
    YAMLPrettyPrinter.method(:print)
  end

  table = TTY::Table.new header: TableHeader do |t|
    changes.each do |change|
      t << print_change(change: change, pretty_print: pretty_print)
    end
  end

  table.render(:ascii, multiline: true, padding: [0, 1, 0, 1])
end

Private Instance Methods

normalize_api_attributes(record, attrs) click to toggle source
# File lib/kong_schema/reporter.rb, line 81
def normalize_api_attributes(record, attrs)
  case record
  when Kong::Api
    attrs.merge('methods' => Array(attrs['methods']).join(',').split(','))
  else
    attrs
  end
end
print_change(change:, pretty_print:) click to toggle source
rewrite_record_attributes(record) click to toggle source

This warrants some explanation.

For some Kong API objects like Target, the API will accept “indirect” values for certain parameters like “upstream_id” but in the responses for those APIs, the payload will contain a value different than what we POSTed with. In this example, it will accept an upstream_id of either an actual Upstream.id like “c9633f63-fdaf-4c1c-b9dd-b5a0fa28c780” or an Upstream.name like “some-upstream.kong-service”.

For our purposes, the user doesn't know about Upstream.id, so we don't care to show that value, so we will rewrite it with the value they're meant to input (e.g. target.upstream_id -> target.upstream.name)

# File lib/kong_schema/reporter.rb, line 102
def rewrite_record_attributes(record)
  case record
  when Kong::Api
    record.attributes
  when Kong::Target
    record.attributes.merge('upstream_id' => record.upstream.name)
  else
    record.attributes
  end
end