class DeskApi::Response::FollowRedirects

The {DeskApi::Response::FollowRedirects} middleware follows redirects automatically

@author Thomas Stachl <tstachl@salesforce.com> @copyright Copyright © 2013-2016 Salesforce.com @license BSD 3-Clause License

Constants

MAX_REDIRECT_LIMIT

Redirection limit

REDIRECT_HTTP_CODES

Status codes we need to redirect

Public Instance Methods

call(env) click to toggle source

Wrapps the call to have a limit countdown

# File lib/desk_api/response/follow_redirects.rb, line 48
def call(env)
  perform env, MAX_REDIRECT_LIMIT
end

Private Instance Methods

perform(env, limit) click to toggle source

Performs the call and checks and performs a redirect if the status is one in 301, 302, 303 or 307

@param env [Hash] @param limit [Integer] @raise DeskApi::Error::FollowRedirectError @return [Faraday::Response]

# File lib/desk_api/response/follow_redirects.rb, line 61
def perform(env, limit)
  body     = env[:body]
  response = @app.call(env)

  response.on_complete do |env|
    if REDIRECT_HTTP_CODES.include? response.status
      raise ::DeskApi::Error::FollowRedirectError, response if limit.zero?
      env      = reset_env(env, body, response)
      response = perform(env, limit - 1)
    end
  end

  response
end
reset_env(env, body, response) click to toggle source

Changes the environment based on the response, eg. it sets the new url, resets the body, …

@param env [Hash] @param body [String] @param response [Faraday::Response] @return [Hash]

# File lib/desk_api/response/follow_redirects.rb, line 83
def reset_env(env, body, response)
  env.tap do |env|
    location   = ::URI.parse response['location']

    # ugly hack so attachments will work
    if location.host != env[:url].host
      env[:request_headers] = {}
    end

    env[:url]  = location
    env[:body] = body
    %w(status response response_headers).each{ |k| env.delete k }
  end
end