diff --git a/lib/twitter/connection.rb b/lib/twitter/connection.rb index ab955e70d..90a8cf9a5 100644 --- a/lib/twitter/connection.rb +++ b/lib/twitter/connection.rb @@ -26,19 +26,18 @@ def connection(options={}) :ssl => {:verify => false}, :url => options.fetch(:endpoint, endpoint), } - Faraday.new(default_options.deep_merge(connection_options)) do |builder| - builder.use Twitter::Request::Phoenix if options[:phoenix] + @connection ||=Faraday.new(default_options.deep_merge(connection_options)) do |builder| + builder.use Twitter::Request::Phoenix builder.use Twitter::Request::MultipartWithFile builder.use Twitter::Request::TwitterOAuth, credentials if credentials? builder.use Faraday::Request::Multipart builder.use Faraday::Request::UrlEncoded builder.use Twitter::Request::Gateway, gateway if gateway builder.use Twitter::Response::RaiseClientError - builder.use Twitter::Response::ParseJson unless options[:raw] + builder.use Twitter::Response::ParseJson builder.use Twitter::Response::RaiseServerError builder.adapter(adapter) end end - end end diff --git a/lib/twitter/request.rb b/lib/twitter/request.rb index bc2a1e6dd..7a35dd51d 100644 --- a/lib/twitter/request.rb +++ b/lib/twitter/request.rb @@ -20,7 +20,9 @@ def post(path, params={}, options={}) # Perform an HTTP request def request(method, path, params, options) - response = connection(options).send(method) do |request| + response = connection(options).run_request(method, nil, nil, nil) do |request| + request.options[:phoenix] = true if options[:phoenix] + request.options[:raw] = true if options[:raw] case method.to_sym when :delete, :get request.url(path, params) diff --git a/lib/twitter/request/phoenix.rb b/lib/twitter/request/phoenix.rb index 6fe262802..e52fce171 100644 --- a/lib/twitter/request/phoenix.rb +++ b/lib/twitter/request/phoenix.rb @@ -8,7 +8,7 @@ def call(env) # Not sure what what the X-Phx (Phoenix?) header is for but it's # required to access certain undocumented resources # e.g. GET urls/resolve - env[:request_headers]['X-Phx'] = 'true' + env[:request_headers]['X-Phx'] = 'true' if env[:request][:phoenix] @app.call(env) end diff --git a/lib/twitter/response/parse_json.rb b/lib/twitter/response/parse_json.rb index e1c2d1f89..7fa3dba59 100644 --- a/lib/twitter/response/parse_json.rb +++ b/lib/twitter/response/parse_json.rb @@ -6,18 +6,23 @@ module Response class ParseJson < Faraday::Response::Middleware def parse(body) - case body - when '' - nil - when 'true' - true - when 'false' - false - else - ::MultiJson.decode(body) + case body + when '' + nil + when 'true' + true + when 'false' + false + else + ::MultiJson.decode(body) + end + end + + def on_complete(env) + if respond_to? :parse + env[:body] = parse(env[:body]) unless env[:request][:raw] or [204,304].index env[:status] end end - end end end