Class: Api::ReviewsIo::RatingsFetcher

Inherits:
Object
  • Object
show all
Defined in:
app/services/api/reviews_io/ratings_fetcher.rb

Overview

Caches and batches product rating lookups from Reviews.io.
rubocop:disable Metrics/ClassLength

Constant Summary collapse

CACHE_NAMESPACE =
'reviews_io:product_ratings'
CACHE_TTL =

Ratings don't change frequently, cache longer to reduce API calls

1.hour
EMPTY_SUMMARY =
{ average_rating: nil, review_count: 0 }.freeze
AVERAGE_KEYS =
%w[average_rating rating avg_rating review_rating average_score average].freeze
COUNT_KEYS =
%w[review_count total_reviews count reviews total rating_count].freeze
SKU_KEYS =
%w[sku product_sku product_id id code identifier].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client: Client.new, cache: Rails.cache, logger: Rails.logger) ⇒ RatingsFetcher

Returns a new instance of RatingsFetcher.



17
18
19
20
21
# File 'app/services/api/reviews_io/ratings_fetcher.rb', line 17

def initialize(client: Client.new, cache: Rails.cache, logger: Rails.logger)
  @client = client
  @cache = cache
  @logger = logger
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



15
16
17
# File 'app/services/api/reviews_io/ratings_fetcher.rb', line 15

def cache
  @cache
end

#clientObject (readonly)

Returns the value of attribute client.



15
16
17
# File 'app/services/api/reviews_io/ratings_fetcher.rb', line 15

def client
  @client
end

#loggerObject (readonly)

Returns the value of attribute logger.



15
16
17
# File 'app/services/api/reviews_io/ratings_fetcher.rb', line 15

def logger
  @logger
end

Instance Method Details

#fetch(skus) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'app/services/api/reviews_io/ratings_fetcher.rb', line 23

def fetch(skus)
  normalized_skus = Array(skus).flatten.compact_blank.map(&:to_s).uniq
  return {} if normalized_skus.empty?

  cached_results, missing = read_from_cache(normalized_skus)
  return cached_results if missing.empty?

  remote_results = fetch_remote(missing)
  merge_remote_results(cached_results, missing, remote_results)
end