Last active
December 21, 2017 19:06
-
-
Save SViccari/b0d14e4c1146f7114549af0c92c0b848 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Piranha::CampaignPerformance | |
def initialize(profile_amazon_id:, campaign_amazon_id:, date_range:) | |
@profile_amazon_id = profile_amazon_id | |
@campaign_amazon_id = campaign_amazon_id | |
@date_range = date_range | |
end | |
def all | |
response = piranha_client.get(daily_campaign_performance_uri) | |
handle_response(response) | |
end | |
private | |
attr_reader :profile_amazon_id, :campaign_amazon_id, :date_range | |
def handle_response(response) | |
if response.success? | |
parse_body(response) | |
else | |
log_and_raise_failed_request(response) | |
end | |
end | |
def parse_body(response) | |
performances_in_response(response).map do |campaign_performance_body| | |
deserialize(campaign_performance_body) | |
end | |
end | |
def performances_in_response(response) | |
if response_has_nested_performances?(response) | |
response.parsed_body["performances"] | |
else | |
response.parsed_body | |
end | |
end | |
def response_has_nested_performances?(response) | |
response.parsed_body.any? { |body| body.include?("performances") } | |
end | |
def deserialize(parsed_json) | |
CampaignPerformanceDeserializer.deserialize(parsed_json) | |
end | |
def log_and_raise_failed_request(response) | |
Metric.request_to_piranha_fail( | |
endpoint: daily_campaign_performance_uri, | |
context: {}, | |
error: response.body, | |
) | |
raise Piranha::Error::BAD_RESPONSE | |
end | |
def daily_campaign_performance_uri | |
"/profiles/#{profile_amazon_id}" + | |
"/campaigns/#{campaign_amazon_id}" + | |
"/performance/daily?" + | |
"endDate=#{end_date}&numberOfPeriods=#{num_periods}" | |
end | |
def num_periods | |
date_range.count | |
end | |
def end_date | |
formatted_date(date_range.last) | |
end | |
def formatted_date(date) | |
date.to_date.iso8601 | |
end | |
def piranha_client | |
@_piranha_client ||= Piranha::HttpClient.new | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment