Shopify rails应用从商店域的SessionRepository检索会话

时间:2016-06-22 16:04:10

标签: ruby-on-rails shopify

我正在尝试通过在控制器中创建新会话来创建代理应用程序。代理控制器有一个参数:商店的myshopify.com域。使用它,我想从我的会话存储库中检索该商店的会话并实例化会话。

这就是我现在的代码

class ProxyController < ActionController::Base
  def index
    shop_domain = params[:shop]
    #puts ShopifyApp::SessionRepository.methods.sort
    shop = ShopifyApp::SessionRepository.retrieve(shop_domain)
    ShopifyAPI::Base.activate_session(shop)

这是ShopifyApp :: SessionRepository类

module ShopifyApp
  class SessionRepository
    class ConfigurationError < StandardError; end

    class << self
      def storage=(storage)
        @storage = storage

        unless storage.nil? || self.storage.respond_to?(:store) && self.storage.respond_to?(:retrieve)
          raise ArgumentError, "storage must respond to :store and :retrieve"
        end
      end

      def retrieve(id)
        storage.retrieve(id)
      end

      def store(session)
        storage.store(session)
      end

      def storage
        load_storage || raise(ConfigurationError.new("ShopifySessionRepository.storage is not configured!"))
      end

      private

      def load_storage
        return unless @storage
        @storage.respond_to?(:safe_constantize) ? @storage.safe_constantize : @storage
      end
    end
  end
end

这是存储模块。

module ShopifyApp
  module SessionStorage
    extend ActiveSupport::Concern

    class_methods do
      def store(session)
        shop = self.find_or_initialize_by(shopify_domain: session.url)
        shop.shopify_token = session.token
        shop.save!
        shop.id
      end

      def retrieve(id)
        return unless id

        if shop = self.find_by(id: id)
          ShopifyAPI::Session.new(shop.shopify_domain, shop.shopify_token)
        end
      end
    end

  end
end

因此,检索需要我的数据库中的商店ID(如3),而不是商店的域名(如dev-store.myshopify.com)。

我正在寻找一种在我的代理控制器上检索/创建会话的方法,通过修改Shop模型以便我可以使用商店域检索它,或者以任何其他方式创建允许我使用的会话我的代理控制器上的API调用。

1 个答案:

答案 0 :(得分:1)

我知道这个老了,但我之前遇到过这个问题。没有太多有用的解决方案。

这对我有用:

shop = Shop.find_by(shopify_domain: params[:shop])
shop = ShopifyApp::SessionRepository.retrieve(shop.id)
ShopifyAPI::Base.activate_session(shop)

您应该可以在数据库中按域找到您的商店。因此能够获取特定的id。

相关问题