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

2023-12-24

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

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

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

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

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

Shop.find(1).connect_to_store
ShopifyAPI::Shop.current.name

问题是,在我的 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

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

p.update_sale_tag

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

您将如何重构这段代码?


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

def shopify_api_path
  "https://#{Rails.configuration.shopify_api_key}:#{self.shopify_token}@#{self.shopify_domain}/admin"
end

然后,如果您想访问延迟作业工作人员中特定商店的 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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何处理 Shopify API 与 Shopify gem 的连接? 的相关文章

随机推荐