如何处理 Shopify API 与 Shopify gem 的连接?

Aug*_*sto 4 ruby-on-rails shopify

您好,我正在 Shopify 应用中使用 Shopify gem,我正在寻找有关如何处理与 Shopify 的 API 连接的建议。

我正在使用 webhooks 和 delay_jobs,所以我需要一种方法来打开控制器外部的连接。

目前我将此方法添加到我的 Shop 模型中:

def connect_to_store
  session = ShopifyAPI::Session.new(self.url, self.access_token)
  session.valid?
  ShopifyAPI::Base.activate_session(session)
end
Run Code Online (Sandbox Code Playgroud)

所以我可以很容易地打开连接,例如:

Shop.find(1).connect_to_store
ShopifyAPI::Shop.current.name
Run Code Online (Sandbox Code Playgroud)

问题是,在我的 Product 模块中,我需要在几个方法中打开连接,但我最终多次调用 connect_to_store 方法,我担心在没有真正需要的情况下打开到同一个商店的多个连接。

有没有办法检查一个连接是否已经打开,只有在没有找到另一个连接时才打开一个新连接?

谢谢,奥古斯托

- - - - - - - - - - 更新 - - - - - - - - - -

我更好地解释了我的问题。

假设在我的产品模型中,我想查看给定产品的 compare_at_price 是否大于其价格,在这种情况下,我想向 Shopify 产品添加“促销”标签。

在我的产品模型中,我有:

class Product < ActiveRecord::Base
belongs_to :shop

def get_from_shopify
    self.shop.connect_to_store
    @shopify_p = ShopifyAPI::Product.find(self.shopify_id)
end

def add_tag(tag)
  @shopify_p = self.get_from_shopify

  shopify_p_tags = shopify_p.tags.split(",")
  shopify_p_tags.collect{|x| x.strip!}

  unless shopify_p_tags.include?(tag) 
    shopify_p_tags << tag
    shopify_p_tags.join(",")

    shopify_p.tags = shopify_p_tags
    shopify_p.save
  end
end


def on_sale?
  @shopify_p = self.get_from_shopify
  sale = false

  shopify_p.variants.each do |v|
    unless v.compare_at_price.nil?
      if v.compare_at_price > v.price
        sale = true
      end
    end
  end

  return sale
end

def update_sale_tag
  if self.on_sale?
    self.add_tag("sale")
  end
end

end
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我打电话:

p.update_sale_tag
Run Code Online (Sandbox Code Playgroud)

Shop.connect_to_store 被多次调用,并且在我已经通过身份验证时我进行了多次身份验证。

你会如何重构这段代码?

小智 5

我通过将 Shopify 返回的 OAuth 令牌存储在商店中来解决这个问题(无论如何你应该这样做)。访问 API 所需的只是令牌,因此在您的商店模型中,您将拥有如下方法:

def shopify_api_path
  "https://#{Rails.configuration.shopify_api_key}:#{self.shopify_token}@#{self.shopify_domain}/admin"
end
Run Code Online (Sandbox Code Playgroud)

然后,如果您想访问延迟作业工作者中特定商店的 API,您只需:

begin
  ShopifyAPI::Base.site = shop.shopify_api_path
  # Make whatever calls to the API that you want here.
  products = ShopifyAPI::Product.all
ensure
  ShopifyAPI::Base.site = nil
end
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助。我发现在控制器之外使用 Sessions 有点麻烦,特别是因为这很好而且很容易。