嗨,我正在我的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产品添加一个"sale“标签。
在我的产品模型中我有:
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_tagShop.connect_to_store被多次调用,并且在我已经通过身份验证时进行了多次身份验证。
你会如何重构这段代码?
发布于 2012-07-12 05:54:02
我通过存储由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希望这能帮点忙。我发现在控制器之外使用会话有点麻烦,特别是因为这很简单。
发布于 2012-07-12 01:32:01
一旦你的应用程序认证过一次,你就可以保留这个计算出来的密码了--这是很好的,直到应用程序被卸载到那个特定的商店。
换句话说,当商家第一次安装应用程序时,只进行一次身份验证,将密码保存到db,并在需要时加载它。然后,您的self.shop.connect_to_store调用应该只设置ShopifyAPI::Session实例。
发布于 2012-07-11 17:35:20
我想这里有些误会。你知道你真的只是在所有的API工作中使用Active Resource吗?因此,当您进行身份验证时,您可能是在验证会话吗?一旦经过验证,不管您实际使用了多少次API,您实际上都不会打开“新”连接。
如果您经常在单个会话中进行身份验证以执行多个API调用,那么您就做错了。
如果您碰巧在没有身份验证的代码块中(例如,您的应用程序可能处理N家商店的WebHook )或延迟作业,只需将myshopify_domain字符串传递给这些代码块,在DB中查找Shop,查找auth令牌,验证(一次).然后你离开..。真的很简单。
https://stackoverflow.com/questions/11437716
复制相似问题