module SolidusBling class Product < ApplicationRecord belongs_to :account def self.update bling_account bling_api = SolidusBling::Api.new(bling_account) skus = ::Spree::Variant.pluck(:sku) hash_products = {} products = skus.map do |sku| begin attempts ||= 1 req = Typhoeus.get("#{bling_api.account.api_base_url}/produtos?codigo=#{sku}", headers: bling_api.headers) res_json = JSON.parse(req.body) # p "#{sku} => #{res_json}" next if res_json["data"] == [] product = res_json["data"].first hash_products[sku] = product["id"] { account_id: bling_api.account.id, sku: sku, external_id: product["id"].to_s, name: product["nome"] } rescue => e hash_products[sku] = res_json # p "#{sku} => #{res_json} => #{e}" sleep 1 retry if (attempts += 1) < 5 end end.compact.uniq SolidusBling::Product.upsert_all(products, unique_by: :sku) ::Spree::Bus.publish :bling_products_updated, products: hash_products end end end