class PDC::Response::Parser

Converts body into JSON data, metadata and errors

Public Instance Methods

parse(body) click to toggle source
# File lib/pdc/http/response/parser.rb, line 10
def parse(body)
  logger.debug "\n.....parse to json ....................................."
  logger.debug self.class

  logger.debug '... parsing' + body.to_s.truncate(55)
  begin
    json = MultiJson.load(body, symbolize_keys: true)
  rescue MultiJson::ParseError => e
    raise PDC::JsonParseError, e
  end

  {
    data:     extract_data(json),     # Always an Array
    errors:   extract_errors(json),   #
    metadata: extract_metadata(json)  # a hash
  }
end

Private Instance Methods

data_only?(json) click to toggle source
# File lib/pdc/http/response/parser.rb, line 58
def data_only?(json)
  json.is_a? Array
end
error?(json) click to toggle source
# File lib/pdc/http/response/parser.rb, line 54
def error?(json)
  json.is_a?(Hash) && json.keys == [:detail]
end
extract_data(json) click to toggle source
# File lib/pdc/http/response/parser.rb, line 30
def extract_data(json)
  return [] if error?(json)
  return json[:results] if metadata_present?(json)
  Array.wrap(json)
end
extract_errors(json) click to toggle source
# File lib/pdc/http/response/parser.rb, line 36
def extract_errors(json)
  error?(json) ? json[:details] : []
end
extract_metadata(json) click to toggle source
# File lib/pdc/http/response/parser.rb, line 40
def extract_metadata(json)
  return json.except(:details, :results) if metadata_present?(json)
  data_only?(json) ? { count: json.length, next: nil, previous: nil } : {}
end
metadata_present?(json) click to toggle source
# File lib/pdc/http/response/parser.rb, line 45
def metadata_present?(json)
  return false if data_only?(json) || error?(json)

  json[:results].is_a?(Array) &&
    json[:count].is_a?(Numeric) &&
    json.key?(:next) &&
    json.key?(:previous)
end