Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Adding support for streamed responses #6

Merged
merged 1 commit into from Jul 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 20 additions & 1 deletion lib/faraday/adapter/net_http_persistent.rb
Expand Up @@ -50,7 +50,26 @@ def proxy_uri(env)
end

def perform_request(http, env)
http.request env[:url], create_request(env)
if env[:request].stream_response?
size = 0
yielded = false

http_response = http.request(env[:url], create_request(env)) do |response|
response.read_body do |chunk|
if chunk.bytesize.positive? || size.positive?
yielded = true
size += chunk.bytesize
env[:request].on_data.call(chunk, size)
end
end
end

env[:request].on_data.call(+"", 0) unless yielded
http_response.body = nil
http_response
else
http.request(env[:url], create_request(env))
end
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This approach is based on https://github.com/lostisland/faraday-net_http/blob/9534fd19bd4898f28361ea60dbc3867edadc15ad/lib/faraday/adapter/net_http.rb#L106-L120

Though I'm happy to hear if you think there is a better way :)

rescue Errno::ETIMEDOUT, Net::OpenTimeout => e
raise Faraday::TimeoutError, e
rescue Net::HTTP::Persistent::Error => e
Expand Down
2 changes: 1 addition & 1 deletion spec/faraday/adapter/net_http_persistent_spec.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true

RSpec.describe Faraday::Adapter::NetHttpPersistent do
features :request_body_on_query_methods, :reason_phrase_parse, :compression, :trace_method
features :request_body_on_query_methods, :reason_phrase_parse, :compression, :trace_method, :streaming

it_behaves_like "an adapter"

Expand Down