class MedlineplusRuby::API::ResponsePayload

Public Class Methods

new() click to toggle source
# File lib/medlineplus_ruby/api/response_payload.rb, line 8
def initialize
end

Public Instance Methods

respond(api_response_body) click to toggle source

Currently only supports 'application/json' responses.

# File lib/medlineplus_ruby/api/response_payload.rb, line 12
def respond(api_response_body)
  formatted_response = {
    success: false,
    errors: [],
    data_requested: nil,
    data: [],
    response_raw: api_response_body
  }

  begin
    parsed_body = JSON.parse api_response_body, symbolize_names: true
  rescue JSON::ParserError => e
    formatted_response[:errors] << MedlineplusRuby::API::ResponseMessage::ERROR_NO_PARSE
  end

  formatted_response.tap do |h|
    h[:success]        = true
    h[:data_requested] = parsed_body.dig :feed, :subtitle, :_value

    parsed_body[:feed][:entry].each do |entry|
      h[:data] << {
        title:       entry[:title][:_value],
        link:        entry[:link].first[:href],
        description: entry[:summary][:_value]
      }
    end if !!parsed_body[:feed][:entry]
  end if !!parsed_body

  formatted_response
end