Class: Fme::Api::FaradayFollowNextLinks
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Fme::Api::FaradayFollowNextLinks
- Defined in:
- lib/fme/api/faraday_follow_next_links.rb
Constant Summary collapse
- ENV_TO_CLEAR =
%i[status response response_headers].to_set.freeze
Instance Attribute Summary collapse
-
#max_pages ⇒ Object
readonly
Returns the value of attribute max_pages.
Instance Method Summary collapse
- #call(env) ⇒ Object
- #handle_response(env, request_body, response_env, max_pages_left) ⇒ Object
-
#initialize(app, max_pages = nil) ⇒ FaradayFollowNextLinks
constructor
A new instance of FaradayFollowNextLinks.
- #next_link(env) ⇒ Object
- #perform_with_next_links(env, max_pages_left) ⇒ Object
- #update_env(env, request_body, next_link) ⇒ Object
Constructor Details
#initialize(app, max_pages = nil) ⇒ FaradayFollowNextLinks
Returns a new instance of FaradayFollowNextLinks.
9 10 11 12 |
# File 'lib/fme/api/faraday_follow_next_links.rb', line 9 def initialize(app, max_pages = nil) super(app) @max_pages = max_pages end |
Instance Attribute Details
#max_pages ⇒ Object (readonly)
Returns the value of attribute max_pages.
7 8 9 |
# File 'lib/fme/api/faraday_follow_next_links.rb', line 7 def max_pages @max_pages end |
Instance Method Details
#call(env) ⇒ Object
14 15 16 17 |
# File 'lib/fme/api/faraday_follow_next_links.rb', line 14 def call(env) @app.call(env) && return unless :get == env[:method] perform_with_next_links(env, max_pages) end |
#handle_response(env, request_body, response_env, max_pages_left) ⇒ Object
35 36 37 38 39 40 |
# File 'lib/fme/api/faraday_follow_next_links.rb', line 35 def handle_response(env, request_body, response_env, max_pages_left) return unless env[:body].is_a?(Array) new_request_env = update_env(response_env.dup, request_body, next_link(env)) max_pages_left -= 1 unless max_pages_left.nil? env[:body] += perform_with_next_links(new_request_env, max_pages_left).body end |
#next_link(env) ⇒ Object
31 32 33 |
# File 'lib/fme/api/faraday_follow_next_links.rb', line 31 def next_link(env) env.response.headers.fetch('x-link-next', nil) end |
#perform_with_next_links(env, max_pages_left) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/fme/api/faraday_follow_next_links.rb', line 19 def perform_with_next_links(env, max_pages_left) request_body = env[:body] response = @app.call(env) response.on_complete do |response_env| if next_link(env).present? raise FaradayMiddleware::RedirectLimitReached, response if max_pages_left == 0 handle_response(env, request_body, response_env, max_pages_left) end end response end |
#update_env(env, request_body, next_link) ⇒ Object
42 43 44 45 46 47 |
# File 'lib/fme/api/faraday_follow_next_links.rb', line 42 def update_env(env, request_body, next_link) env[:url] = URI.parse(next_link) env[:body] = request_body ENV_TO_CLEAR.each { |key| env.delete key } env end |