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.

Constant Summary collapse

CACHE_NAMESPACE =

Cache namespace.

'reviews_io:product_ratings'
CACHE_TTL =

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

1.hour
EMPTY_SUMMARY =

Empty summary.

{ average_rating: nil, review_count: 0 }.freeze
AVERAGE_KEYS =

Keys used for average.

%w[average_rating rating avg_rating review_rating average_score average].freeze
COUNT_KEYS =

Keys used for count.

%w[review_count total_reviews count reviews total rating_count].freeze
SKU_KEYS =

Keys used for sku.

%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.



21
22
23
24
25
# File 'app/services/api/reviews_io/ratings_fetcher.rb', line 21

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.



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

def cache
  @cache
end

#clientObject (readonly)

Returns the value of attribute client.



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

def client
  @client
end

#loggerObject (readonly)

Returns the value of attribute logger.



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

def logger
  @logger
end

Instance Method Details

#fetch(skus) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'app/services/api/reviews_io/ratings_fetcher.rb', line 27

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