Rails 带有 Faraday 的应用程序:在没有 url 参数的情况下重构 Faraday::new() 时出现问题

Rails app with Faraday: Problem refactoring Faraday::new() without url parameter

我正在重构 Rails 应用程序中的一些代码,其中包含多个微服务。 faraday_middleware gem 用于服务之间的通信。

我设法用 ServiceConnectionHelper 模块中对 Faraday::new() 的一次调用替换了不同帮助程序文件中对 Faraday::new() 的多次调用。所有这些被替换的调用都有一个 url 参数:Faraday.new(url: url)

但是还有两段非常相似的代码我想去掉。在这些情况下,没有 url 参数。这是旧的(有效的)代码:

# This code calls the connection function below
def create(resource)
  params = {
    resource_id: resource.to_param,
    version: resource.version,
    file: Faraday::UploadIO.new(resource.file.path, resource.mime_type.to_s, resource.file.original_filename)
  }

  res = connection(resource.authorization).post(foobar_url, params)
  return res.body['id'] if [200, 201].include?(res.status)
  raise UploadError, res.body['error']
end

# connection function
def connection(authorization_header = nil)
  Faraday.new do |conn|
    conn.use FaradayMiddleware::FollowRedirects, limit: 5
    conn.request :multipart
    conn.request :url_encoded
    conn.use FaradayMiddleware::ParseJson, content_type: 'application/json'
    conn.adapter Faraday.default_adapter
    conn.headers['Accept'] = 'application/json'
    conn.headers['Authorization'] = authorization_header unless authorization_header.nil?
  end
end

这是我想改用的代码。由于 create 函数内部的错误,它无法正常工作。当我捕获并记录它时,e.inspect 只是 #<UploadError: Please specify a file>

# Small change only: Te other service's url is computed in the ServiceConnectionHelper module
def create(resource)
  params = {
    resource_id: resource.to_param,
    version: resource.version,
    file: Faraday::UploadIO.new(resource.file.path, resource.mime_type.to_s, resource.file.original_filename)
        }

  # This is were the error happens
  res = connection(resource.authorization).post('/', params)
  return res.body['id'] if [200, 201].include?(res.status)
  raise UploadError, res.body['error']
end

# connection function calls the new helper module now
def connection(authorization_header = nil)
  ServiceConnectionHelper.connection('foobar', authorization_header)
end

# the new module
module ServiceConnectionHelper
  class << self
    def connection(service, oauth_token = nil)

      url = service_url(service)

      Faraday.new(url: url) do |conn|
        conn.use FaradayMiddleware::FollowRedirects, limit: 5
        conn.request :url_encoded
        conn.adapter Faraday.default_adapter
        conn.request :multipart
        conn.use FaradayMiddleware::ParseJson, content_type: 'application/json'
        conn.headers['Accept'] = 'application/json'

        conn.headers['Authorization'] = oauth_token if oauth_token
      end
    end

    private

    def service_url(service)
      url = case service
      when 'foobar' then 'foobar_url_as_a_string'
      # the same for other services  
      end

      url
    end
  end
end

在这种情况下,我该怎么做才能使 ServiceConnectionHelper 正常工作?

与您的第一个示例相比,request 的顺序发生了变化:

conn.request :url_encoded
conn.request :multipart