faraday_middleware 0.14.0 → 1.0.0.rc1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e7beabdfd775a267ce0c8be26be6d42177d2b586e39ac1f4e8e2e07d9554ea53
4
- data.tar.gz: c06131c5aaaea0affda0f77c3459da0ce3f2404c437893fb088a41ebbc502313
3
+ metadata.gz: 28522d3a469097ac904270bfc69c6775eac586c95d910d65eea4f98a062f3cdd
4
+ data.tar.gz: a0e9dea7658b3df3045375c9104d8e29be68f885d4a8999e27bbc44608ea6208
5
5
  SHA512:
6
- metadata.gz: bca7b8a07b9113d6e1df94e2b5ec426496bc914f04d76bc4c755dcaf4d57d33cf0f85c68db94103acc197860428191bc838b79ef8187f682749eba2523add633
7
- data.tar.gz: 35dc075c2606f365407947c3f24be9c6e1d9b59948198d532ab3254c6ae3b1fd975de519a9e80b054cb807c204c5b23be13ba17ca59014b05063facc07bd4c5c
6
+ metadata.gz: dcd643bd90576c5cefe3bee77b70e2b0e85bb6730f30f9b71502036ea30641f56b94414992d34d1d25be97e3e6f6a976c53143cf665d5c081dd42a147b96b4c3
7
+ data.tar.gz: 2d4a7e028105a9e4f1b58f85dfde3bed7a7db5f6b8342b3f631b2a30f5e0b997dd6dba443b56d5223f801d5b1a68e9ab05b1b8b420b9b6339c1389befe84817f
data/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  Faraday Middleware
2
2
  ==================
3
3
  [![Gem Version](https://badge.fury.io/rb/faraday_middleware.svg)](https://rubygems.org/gems/faraday_middleware)
4
- [![Build Status](https://travis-ci.org/lostisland/faraday_middleware.svg)](https://travis-ci.org/lostisland/faraday_middleware)
4
+ ![GitHub Actions CI](https://github.com/lostisland/faraday_middleware/workflows/CI/badge.svg)
5
5
  [![Maintainability](https://api.codeclimate.com/v1/badges/a971ee5025b269c39d93/maintainability)](https://codeclimate.com/github/lostisland/faraday_middleware/maintainability)
6
6
 
7
7
  A collection of useful [Faraday][] middleware. [See the documentation][docs].
@@ -11,6 +11,10 @@ A collection of useful [Faraday][] middleware. [See the documentation][docs].
11
11
  Dependencies
12
12
  ------------
13
13
 
14
+ Ruby >= 2.3.0
15
+
16
+ #### As of v0.16.0, `faraday` and `faraday_middleware` no longer officially support JRuby or Rubinius.
17
+
14
18
  Some dependent libraries are needed only when using specific middleware:
15
19
 
16
20
  | Middleware | Library | Notes |
@@ -28,29 +32,16 @@ Examples
28
32
  ``` rb
29
33
  require 'faraday_middleware'
30
34
 
31
- ## in Faraday 0.8 or above:
32
35
  connection = Faraday.new 'http://example.com/api' do |conn|
33
36
  conn.request :oauth2, 'TOKEN'
34
37
  conn.request :json
35
38
 
36
- conn.response :xml, :content_type => /\bxml$/
37
- conn.response :json, :content_type => /\bjson$/
39
+ conn.response :xml, content_type: /\bxml$/
40
+ conn.response :json, content_type: /\bjson$/
38
41
 
39
42
  conn.use :instrumentation
40
43
  conn.adapter Faraday.default_adapter
41
44
  end
42
-
43
- ## with Faraday 0.7:
44
- connection = Faraday.new 'http://example.com/api' do |builder|
45
- builder.use FaradayMiddleware::OAuth2, 'TOKEN'
46
- builder.use FaradayMiddleware::EncodeJson
47
-
48
- builder.use FaradayMiddleware::ParseXml, :content_type => /\bxml$/
49
- builder.use FaradayMiddleware::ParseJson, :content_type => /\bjson$/
50
-
51
- builder.use FaradayMiddleware::Instrumentation
52
- builder.adapter Faraday.default_adapter
53
- end
54
45
  ```
55
46
 
56
47
 
@@ -1,5 +1,8 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
 
5
+ # Main FaradayMiddleware module.
3
6
  module FaradayMiddleware
4
7
  autoload :OAuth, 'faraday_middleware/request/oauth'
5
8
  autoload :OAuth2, 'faraday_middleware/request/oauth2'
@@ -15,33 +18,34 @@ module FaradayMiddleware
15
18
  autoload :Caching, 'faraday_middleware/response/caching'
16
19
  autoload :Chunked, 'faraday_middleware/response/chunked'
17
20
  autoload :RackCompatible, 'faraday_middleware/rack_compatible'
21
+ autoload :RedirectLimitReached, 'faraday_middleware/redirect_limit_reached'
18
22
  autoload :FollowRedirects, 'faraday_middleware/response/follow_redirects'
19
23
  autoload :Instrumentation, 'faraday_middleware/instrumentation'
20
24
  autoload :Gzip, 'faraday_middleware/gzip'
21
25
 
22
26
  if Faraday::Middleware.respond_to? :register_middleware
23
27
  Faraday::Request.register_middleware \
24
- :oauth => lambda { OAuth },
25
- :oauth2 => lambda { OAuth2 },
26
- :json => lambda { EncodeJson },
27
- :method_override => lambda { MethodOverride }
28
+ oauth: -> { OAuth },
29
+ oauth2: -> { OAuth2 },
30
+ json: -> { EncodeJson },
31
+ method_override: -> { MethodOverride }
28
32
 
29
33
  Faraday::Response.register_middleware \
30
- :mashify => lambda { Mashify },
31
- :rashify => lambda { Rashify },
32
- :json => lambda { ParseJson },
33
- :json_fix => lambda { ParseJson::MimeTypeFix },
34
- :xml => lambda { ParseXml },
35
- :marshal => lambda { ParseMarshal },
36
- :yaml => lambda { ParseYaml },
37
- :dates => lambda { ParseDates },
38
- :caching => lambda { Caching },
39
- :follow_redirects => lambda { FollowRedirects },
40
- :chunked => lambda { Chunked }
34
+ mashify: -> { Mashify },
35
+ rashify: -> { Rashify },
36
+ json: -> { ParseJson },
37
+ json_fix: -> { ParseJson::MimeTypeFix },
38
+ xml: -> { ParseXml },
39
+ marshal: -> { ParseMarshal },
40
+ yaml: -> { ParseYaml },
41
+ dates: -> { ParseDates },
42
+ caching: -> { Caching },
43
+ follow_redirects: -> { FollowRedirects },
44
+ chunked: -> { Chunked }
41
45
 
42
46
  Faraday::Middleware.register_middleware \
43
- :instrumentation => lambda { Instrumentation },
44
- :gzip => lambda { Gzip }
47
+ instrumentation: -> { Instrumentation },
48
+ gzip: -> { Gzip }
45
49
  end
46
50
  end
47
51
 
@@ -1,11 +1,13 @@
1
- # deprecated constants
1
+ # frozen_string_literal: true
2
2
 
3
3
  module Faraday
4
+ # Autoload classes for Faraday::Request.
4
5
  class Request
5
6
  autoload :OAuth, 'faraday_middleware/request/oauth'
6
7
  autoload :OAuth2, 'faraday_middleware/request/oauth2'
7
8
  end
8
9
 
10
+ # Autoload classes for Faraday::Request.
9
11
  class Response
10
12
  autoload :Mashify, 'faraday_middleware/response/mashify'
11
13
  autoload :Rashify, 'faraday_middleware/response/rashify'
@@ -15,4 +17,3 @@ module Faraday
15
17
  autoload :ParseYaml, 'faraday_middleware/response/parse_yaml'
16
18
  end
17
19
  end
18
-
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
 
3
5
  module FaradayMiddleware
@@ -28,11 +30,10 @@ module FaradayMiddleware
28
30
  encodings
29
31
  end
30
32
 
31
- ACCEPT_ENCODING = 'Accept-Encoding'.freeze
32
- CONTENT_ENCODING = 'Content-Encoding'.freeze
33
- CONTENT_LENGTH = 'Content-Length'.freeze
33
+ ACCEPT_ENCODING = 'Accept-Encoding'
34
+ CONTENT_ENCODING = 'Content-Encoding'
35
+ CONTENT_LENGTH = 'Content-Length'
34
36
  SUPPORTED_ENCODINGS = supported_encodings.join(',').freeze
35
- RUBY_ENCODING = '1.9'.respond_to?(:force_encoding)
36
37
 
37
38
  def call(env)
38
39
  env[:request_headers][ACCEPT_ENCODING] ||= SUPPORTED_ENCODINGS
@@ -60,11 +61,7 @@ module FaradayMiddleware
60
61
 
61
62
  def uncompress_gzip(body)
62
63
  io = StringIO.new(body)
63
- gzip_reader = if RUBY_ENCODING
64
- Zlib::GzipReader.new(io, :encoding => 'ASCII-8BIT')
65
- else
66
- Zlib::GzipReader.new(io)
67
- end
64
+ gzip_reader = Zlib::GzipReader.new(io, encoding: 'ASCII-8BIT')
68
65
  gzip_reader.read
69
66
  end
70
67
 
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
 
3
5
  module FaradayMiddleware
@@ -7,11 +9,15 @@ module FaradayMiddleware
7
9
  #
8
10
  # Examples
9
11
  #
10
- # ActiveSupport::Notifications.subscribe('request.faraday') do |name, starts, ends, _, env|
12
+ # ActiveSupport::Notifications.
13
+ # subscribe('request.faraday') do |name, starts, ends, _, env|
11
14
  # url = env[:url]
12
15
  # http_method = env[:method].to_s.upcase
13
16
  # duration = ends - starts
14
- # $stderr.puts '[%s] %s %s (%.3f s)' % [url.host, http_method, url.request_uri, duration]
17
+ # $stderr.puts '[%s] %s %s (%.3f s)' % [url.host,
18
+ # http_method,
19
+ # url.request_uri,
20
+ # duration]
15
21
  # end
16
22
  class Instrumentation < Faraday::Middleware
17
23
  dependency 'active_support/notifications'
@@ -1,7 +1,9 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'stringio'
2
4
 
3
5
  module FaradayMiddleware
4
- # Wraps a handler originally written for Rack to make it compatible with Faraday.
6
+ # Wraps a handler originally written for Rack for Faraday compatibility.
5
7
  #
6
8
  # Experimental. Only handles changes in request headers.
7
9
  class RackCompatible
@@ -22,7 +24,7 @@ module FaradayMiddleware
22
24
  finalize_response(env, rack_response)
23
25
  end
24
26
 
25
- NonPrefixedHeaders = %w[CONTENT_LENGTH CONTENT_TYPE]
27
+ NON_PREFIXED_HEADERS = %w[CONTENT_LENGTH CONTENT_TYPE].freeze
26
28
 
27
29
  # faraday to rack-compatible
28
30
  def prepare_env(faraday_env)
@@ -31,7 +33,11 @@ module FaradayMiddleware
31
33
  url = faraday_env[:url]
32
34
  env['rack.url_scheme'] = url.scheme
33
35
  env['PATH_INFO'] = url.path
34
- env['SERVER_PORT'] = url.respond_to?(:inferred_port) ? url.inferred_port : url.port
36
+ env['SERVER_PORT'] = if url.respond_to?(:inferred_port)
37
+ url.inferred_port
38
+ else
39
+ url.port
40
+ end
35
41
  env['QUERY_STRING'] = url.query
36
42
  env['REQUEST_METHOD'] = faraday_env[:method].to_s.upcase
37
43
 
@@ -45,7 +51,7 @@ module FaradayMiddleware
45
51
  rack_env = {}
46
52
  env[:request_headers].each do |name, value|
47
53
  name = name.upcase.tr('-', '_')
48
- name = "HTTP_#{name}" unless NonPrefixedHeaders.include? name
54
+ name = "HTTP_#{name}" unless NON_PREFIXED_HEADERS.include? name
49
55
  rack_env[name] = value
50
56
  end
51
57
  rack_env
@@ -58,8 +64,9 @@ module FaradayMiddleware
58
64
  headers.clear
59
65
 
60
66
  rack_env.each do |name, value|
61
- next unless String === name && String === value
62
- if NonPrefixedHeaders.include? name or name.index('HTTP_') == 0
67
+ next unless name.is_a?(String) && value.is_a?(String)
68
+
69
+ if NON_PREFIXED_HEADERS.include?(name) || name.start_with?('HTTP_')
63
70
  name = name.sub(/^HTTP_/, '').downcase.tr('_', '-')
64
71
  headers[name] = value
65
72
  end
@@ -72,12 +79,14 @@ module FaradayMiddleware
72
79
 
73
80
  def finalize_response(env, rack_response)
74
81
  status, headers, body = rack_response
75
- body = body.inject() { |str, part| str << part }
76
- headers = Faraday::Utils::Headers.new(headers) unless Faraday::Utils::Headers === headers
82
+ body = body.inject { |str, part| str << part }
83
+ unless headers.is_a?(Faraday::Utils::Headers)
84
+ headers = Faraday::Utils::Headers.new(headers)
85
+ end
77
86
 
78
- env.update :status => status.to_i,
79
- :body => body,
80
- :response_headers => headers
87
+ env.update status: status.to_i,
88
+ body: body,
89
+ response_headers: headers
81
90
 
82
91
  env[:response] ||= Faraday::Response.new(env)
83
92
  env[:response]
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'faraday'
4
+
5
+ module FaradayMiddleware
6
+ # Exception thrown when the maximum amount of requests is
7
+ # exceeded.
8
+ class RedirectLimitReached < Faraday::ClientError
9
+ attr_reader :response
10
+
11
+ def initialize(response)
12
+ super "too many redirects; last one to: #{response['location']}"
13
+ @response = response
14
+ end
15
+ end
16
+ end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
 
3
5
  module FaradayMiddleware
@@ -9,9 +11,9 @@ module FaradayMiddleware
9
11
  #
10
12
  # Doesn't try to encode bodies that already are in string form.
11
13
  class EncodeJson < Faraday::Middleware
12
- CONTENT_TYPE = 'Content-Type'.freeze
13
- MIME_TYPE = 'application/json'.freeze
14
- MIME_TYPE_REGEX = /^application\/(vnd\..+\+)?json$/
14
+ CONTENT_TYPE = 'Content-Type'
15
+ MIME_TYPE = 'application/json'
16
+ MIME_TYPE_REGEX = %r{^application/(vnd\..+\+)?json$}.freeze
15
17
 
16
18
  dependency do
17
19
  require 'json' unless defined?(::JSON)
@@ -29,19 +31,19 @@ module FaradayMiddleware
29
31
  end
30
32
 
31
33
  def match_content_type(env)
32
- if process_request?(env)
33
- env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE
34
- yield env[:body] unless env[:body].respond_to?(:to_str)
35
- end
34
+ return unless process_request?(env)
35
+
36
+ env[:request_headers][CONTENT_TYPE] ||= MIME_TYPE
37
+ yield env[:body] unless env[:body].respond_to?(:to_str)
36
38
  end
37
39
 
38
40
  def process_request?(env)
39
41
  type = request_type(env)
40
- has_body?(env) and (type.empty? or MIME_TYPE_REGEX =~ type)
42
+ has_body?(env) && (type.empty? || MIME_TYPE_REGEX =~ type)
41
43
  end
42
44
 
43
45
  def has_body?(env)
44
- body = env[:body] and !(body.respond_to?(:to_str) and body.empty?)
46
+ (body = env[:body]) && !(body.respond_to?(:to_str) && body.empty?)
45
47
  end
46
48
 
47
49
  def request_type(env)
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
 
3
5
  module FaradayMiddleware
@@ -11,8 +13,7 @@ module FaradayMiddleware
11
13
  # Rack::MethodOverride module. See
12
14
  # http://rack.rubyforge.org/doc/classes/Rack/MethodOverride.html
13
15
  class MethodOverride < Faraday::Middleware
14
-
15
- HEADER = "X-Http-Method-Override".freeze
16
+ HEADER = 'X-Http-Method-Override'
16
17
 
17
18
  # Public: Initialize the middleware.
18
19
  #
@@ -22,10 +23,10 @@ module FaradayMiddleware
22
23
  # (default: all but GET and POST)
23
24
  def initialize(app, options = nil)
24
25
  super(app)
25
- @methods = options && options.fetch(:rewrite).map { |method|
26
+ @methods = options&.fetch(:rewrite)&.map do |method|
26
27
  method = method.downcase if method.respond_to? :downcase
27
28
  method.to_sym
28
- }
29
+ end
29
30
  end
30
31
 
31
32
  def call(env)
@@ -35,8 +36,8 @@ module FaradayMiddleware
35
36
  end
36
37
 
37
38
  def rewrite_request?(method)
38
- if @methods.nil? or @methods.empty?
39
- method != :get and method != :post
39
+ if @methods.nil? || @methods.empty?
40
+ (method != :get) && (method != :post)
40
41
  else
41
42
  @methods.include? method
42
43
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
  require 'forwardable'
3
5
 
@@ -23,14 +25,12 @@ module FaradayMiddleware
23
25
  class OAuth < Faraday::Middleware
24
26
  dependency 'simple_oauth'
25
27
 
26
- AUTH_HEADER = 'Authorization'.freeze
27
- CONTENT_TYPE = 'Content-Type'.freeze
28
- TYPE_URLENCODED = 'application/x-www-form-urlencoded'.freeze
28
+ AUTH_HEADER = 'Authorization'
29
+ CONTENT_TYPE = 'Content-Type'
30
+ TYPE_URLENCODED = 'application/x-www-form-urlencoded'
29
31
 
30
32
  extend Forwardable
31
- parser_method = :parse_nested_query
32
- parser_module = ::Faraday::Utils.respond_to?(parser_method) ? 'Faraday::Utils' : 'Rack::Utils'
33
- def_delegator parser_module, parser_method
33
+ def_delegator :'Faraday::Utils', :parse_nested_query
34
34
 
35
35
  def initialize(app, options)
36
36
  super(app)
@@ -38,7 +38,9 @@ module FaradayMiddleware
38
38
  end
39
39
 
40
40
  def call(env)
41
- env[:request_headers][AUTH_HEADER] ||= oauth_header(env).to_s if sign_request?(env)
41
+ if sign_request?(env)
42
+ env[:request_headers][AUTH_HEADER] ||= oauth_header(env).to_s
43
+ end
42
44
  @app.call(env)
43
45
  end
44
46
 
@@ -54,7 +56,7 @@ module FaradayMiddleware
54
56
  end
55
57
 
56
58
  def oauth_options(env)
57
- if extra = env[:request][:oauth] and extra.is_a? Hash and !extra.empty?
59
+ if (extra = env[:request][:oauth]) && extra.is_a?(Hash) && !extra.empty?
58
60
  @options.merge extra
59
61
  else
60
62
  @options
@@ -73,12 +75,15 @@ module FaradayMiddleware
73
75
 
74
76
  def include_body_params?(env)
75
77
  # see RFC 5849, section 3.4.1.3.1 for details
76
- !(type = env[:request_headers][CONTENT_TYPE]) or type == TYPE_URLENCODED
78
+ !(type = env[:request_headers][CONTENT_TYPE]) || (type == TYPE_URLENCODED)
77
79
  end
78
80
 
79
81
  def signature_params(params)
80
- params.empty? ? params :
81
- params.reject {|k,v| v.respond_to?(:content_type) }
82
+ if params.empty?
83
+ params
84
+ else
85
+ params.reject { |_k, v| v.respond_to?(:content_type) }
86
+ end
82
87
  end
83
88
  end
84
89
  end
@@ -1,14 +1,17 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
  require 'forwardable'
3
5
 
4
6
  module FaradayMiddleware
5
7
  # Public: A simple middleware that adds an access token to each request.
6
8
  #
7
- # By default, the token is added as both "access_token" query parameter and the
8
- # "Authorization" HTTP request header. It can alternatively be added exclusively
9
- # as a bearer token "Authorization" header by specifying a "token_type" option
10
- # of "bearer". However, an explicit "access_token" parameter or "Authorization"
11
- # header for the current request are not overriden.
9
+ # By default, the token is added as both "access_token" query parameter
10
+ # and the "Authorization" HTTP request header. It can alternatively be
11
+ # added exclusively as a bearer token "Authorization" header by specifying
12
+ # a "token_type" option of "bearer". However, an explicit "access_token"
13
+ # parameter or "Authorization" header for the current request are not
14
+ # overriden.
12
15
  #
13
16
  # Examples
14
17
  #
@@ -24,10 +27,9 @@ module FaradayMiddleware
24
27
  # # default token value is optional:
25
28
  # OAuth2.new(app, :param_name => 'my_oauth_token')
26
29
  class OAuth2 < Faraday::Middleware
27
-
28
- PARAM_NAME = 'access_token'.freeze
29
- TOKEN_TYPE = 'param'.freeze
30
- AUTH_HEADER = 'Authorization'.freeze
30
+ PARAM_NAME = 'access_token'
31
+ TOKEN_TYPE = 'param'
32
+ AUTH_HEADER = 'Authorization'
31
33
 
32
34
  attr_reader :param_name, :token_type
33
35
 
@@ -53,8 +55,11 @@ module FaradayMiddleware
53
55
 
54
56
  def initialize(app, token = nil, options = {})
55
57
  super(app)
56
- options, token = token, nil if token.is_a? Hash
57
- @token = token && token.to_s
58
+ if token.is_a? Hash
59
+ options = token
60
+ token = nil
61
+ end
62
+ @token = token&.to_s
58
63
  @param_name = options.fetch(:param_name, PARAM_NAME).to_s
59
64
  @token_type = options.fetch(:token_type, TOKEN_TYPE).to_s
60
65
 
@@ -62,17 +67,17 @@ module FaradayMiddleware
62
67
  raise ArgumentError, ":param_name can't be blank"
63
68
  end
64
69
 
65
- if options[:token_type].nil?
66
- warn "\nWarning: FaradayMiddleware::OAuth2 initialized with default "\
67
- "token_type - token will be added as both a query string parameter "\
68
- "and an Authorization header. In the next major release, tokens will "\
69
- "be added exclusively as an Authorization header by default. Please "\
70
- "visit https://github.com/lostisland/faraday_middleware/wiki for more information."
71
- end
70
+ return unless options[:token_type].nil?
71
+
72
+ warn "\nWarning: FaradayMiddleware::OAuth2 initialized with default "\
73
+ 'token_type - token will be added as both a query string parameter '\
74
+ 'and an Authorization header. In the next major release, tokens will '\
75
+ 'be added exclusively as an Authorization header by default. Please '\
76
+ 'see https://github.com/lostisland/faraday_middleware/wiki.'
72
77
  end
73
78
 
74
79
  def query_params(url)
75
- if url.query.nil? or url.query.empty?
80
+ if url.query.nil? || url.query.empty?
76
81
  {}
77
82
  else
78
83
  parse_query url.query
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
  require 'forwardable'
3
5
  require 'digest/sha1'
@@ -14,7 +16,7 @@ module FaradayMiddleware
14
16
  # * 302 - 'Found'
15
17
  # * 404 - 'Not Found'
16
18
  # * 410 - 'Gone'
17
- CACHEABLE_STATUS_CODES = [200, 203, 300, 301, 302, 404, 410]
19
+ CACHEABLE_STATUS_CODES = [200, 203, 300, 301, 302, 404, 410].freeze
18
20
 
19
21
  extend Forwardable
20
22
  def_delegators :'Faraday::Utils', :parse_query, :build_query
@@ -23,31 +25,36 @@ module FaradayMiddleware
23
25
  #
24
26
  # cache - An object that responds to read and write (default: nil).
25
27
  # options - An options Hash (default: {}):
26
- # :ignore_params - String name or Array names of query params
27
- # that should be ignored when forming the cache
28
- # key (default: []).
29
- # :write_options - Hash of settings that should be passed as the third
30
- # options parameter to the cache's #write method. If not
31
- # specified, no options parameter will be passed.
32
- # :full_key - Boolean - use full URL (url.host + url.request_uri) as cache key
28
+ # :ignore_params - String name or Array names of query
29
+ # params that should be ignored when forming
30
+ # the cache key (default: []).
31
+ # :write_options - Hash of settings that should be passed as the
32
+ # third options parameter to the cache's #write
33
+ # method. If not specified, no options parameter
34
+ # will be passed.
35
+ # :full_key - Boolean - use full URL as cache key:
36
+ # (url.host + url.request_uri)
33
37
  #
34
38
  # Yields if no cache is given. The block should return a cache object.
35
39
  def initialize(app, cache = nil, options = {})
36
40
  super(app)
37
- options, cache = cache, nil if cache.is_a? Hash and block_given?
41
+ if cache.is_a?(Hash) && block_given?
42
+ options = cache
43
+ cache = nil
44
+ end
38
45
  @cache = cache || yield
39
46
  @options = options
40
47
  end
41
48
 
42
49
  def call(env)
43
- if :get == env[:method]
50
+ if env[:method] == :get
44
51
  if env[:parallel_manager]
45
52
  # callback mode
46
53
  cache_on_complete(env)
47
54
  else
48
55
  # synchronous mode
49
56
  key = cache_key(env)
50
- unless response = cache.read(key) and response
57
+ unless (response = cache.read(key)) && response
51
58
  response = @app.call(env)
52
59
  store_response_in_cache(key, response)
53
60
  end
@@ -62,15 +69,16 @@ module FaradayMiddleware
62
69
  url = env[:url].dup
63
70
  if url.query && params_to_ignore.any?
64
71
  params = parse_query url.query
65
- params.reject! {|k,| params_to_ignore.include? k }
72
+ params.reject! { |k,| params_to_ignore.include? k }
66
73
  url.query = params.any? ? build_query(params) : nil
67
74
  end
68
75
  url.normalize!
69
- Digest::SHA1.hexdigest(full_key? ? url.host + url.request_uri : url.request_uri)
76
+ digest = full_key? ? url.host + url.request_uri : url.request_uri
77
+ Digest::SHA1.hexdigest(digest)
70
78
  end
71
79
 
72
80
  def params_to_ignore
73
- @params_to_ignore ||= Array(@options[:ignore_params]).map { |p| p.to_s }
81
+ @params_to_ignore ||= Array(@options[:ignore_params]).map(&:to_s)
74
82
  end
75
83
 
76
84
  def full_key?
@@ -79,10 +87,11 @@ module FaradayMiddleware
79
87
 
80
88
  def cache_on_complete(env)
81
89
  key = cache_key(env)
82
- if cached_response = cache.read(key)
90
+ if (cached_response = cache.read(key))
83
91
  finalize_response(cached_response, env)
84
92
  else
85
- # response.status is nil at this point, any checks need to be done inside on_complete block
93
+ # response.status is nil at this point
94
+ # any checks need to be done inside on_complete block
86
95
  @app.call(env).on_complete do |response_env|
87
96
  store_response_in_cache(key, response_env.response)
88
97
  response_env
@@ -1,16 +1,19 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday_middleware/response_middleware'
2
4
 
3
5
  module FaradayMiddleware
4
- # Public: Parse a Transfer-Encoding: Chunked response to just the original data
6
+ # Public: Parse a Transfer-Encoding. Chunks response to just the original data
5
7
  class Chunked < FaradayMiddleware::ResponseMiddleware
6
- TRANSFER_ENCODING = 'transfer-encoding'.freeze
8
+ TRANSFER_ENCODING = 'transfer-encoding'
7
9
 
8
10
  define_parser do |raw_body|
9
11
  decoded_body = []
10
12
  until raw_body.empty?
11
13
  chunk_len, raw_body = raw_body.split("\r\n", 2)
12
- chunk_len = chunk_len.split(';',2).first.hex
13
- break if chunk_len == 0
14
+ chunk_len = chunk_len.split(';', 2).first.hex
15
+ break if chunk_len.zero?
16
+
14
17
  decoded_body << raw_body[0, chunk_len]
15
18
  # The 2 is to strip the extra CRLF at the end of the chunk
16
19
  raw_body = raw_body[chunk_len + 2, raw_body.length - chunk_len - 2]
@@ -19,11 +22,12 @@ module FaradayMiddleware
19
22
  end
20
23
 
21
24
  def parse_response?(env)
22
- super and chunked_encoding?(env[:response_headers])
25
+ super && chunked_encoding?(env[:response_headers])
23
26
  end
24
27
 
25
28
  def chunked_encoding?(headers)
26
- encoding = headers[TRANSFER_ENCODING] and encoding.split(',').include?('chunked')
29
+ (encoding = headers[TRANSFER_ENCODING]) &&
30
+ encoding.split(',').include?('chunked')
27
31
  end
28
32
  end
29
33
  end
@@ -1,17 +1,9 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
  require 'set'
3
5
 
4
6
  module FaradayMiddleware
5
- # Public: Exception thrown when the maximum amount of requests is exceeded.
6
- class RedirectLimitReached < Faraday::Error::ClientError
7
- attr_reader :response
8
-
9
- def initialize(response)
10
- super "too many redirects; last one to: #{response['location']}"
11
- @response = response
12
- end
13
- end
14
-
15
7
  # Public: Follow HTTP 301, 302, 303, 307, and 308 redirects.
16
8
  #
17
9
  # For HTTP 301, 302, and 303, the original GET, POST, PUT, DELETE, or PATCH
@@ -32,20 +24,20 @@ module FaradayMiddleware
32
24
  # end
33
25
  class FollowRedirects < Faraday::Middleware
34
26
  # HTTP methods for which 30x redirects can be followed
35
- ALLOWED_METHODS = Set.new [:head, :options, :get, :post, :put, :patch, :delete]
27
+ ALLOWED_METHODS = Set.new %i[head options get post put patch delete]
36
28
  # HTTP redirect status codes that this middleware implements
37
29
  REDIRECT_CODES = Set.new [301, 302, 303, 307, 308]
38
30
  # Keys in env hash which will get cleared between requests
39
- ENV_TO_CLEAR = Set.new [:status, :response, :response_headers]
31
+ ENV_TO_CLEAR = Set.new %i[status response response_headers]
40
32
 
41
33
  # Default value for max redirects followed
42
34
  FOLLOW_LIMIT = 3
43
35
 
44
36
  # Regex that matches characters that need to be escaped in URLs, sans
45
37
  # the "%" character which we assume already represents an escaped sequence.
46
- URI_UNSAFE = /[^\-_.!~*'()a-zA-Z\d;\/?:@&=+$,\[\]%]/
38
+ URI_UNSAFE = %r{[^\-_.!~*'()a-zA-Z\d;/?:@&=+$,\[\]%]}.freeze
47
39
 
48
- AUTH_HEADER = 'Authorization'.freeze
40
+ AUTH_HEADER = 'Authorization'
49
41
 
50
42
  # Public: Initialize the middleware.
51
43
  #
@@ -54,7 +46,7 @@ module FaradayMiddleware
54
46
  # :standards_compliant - A Boolean indicating whether to respect
55
47
  # the HTTP spec when following 301/302
56
48
  # (default: false)
57
- # :callback - A callable that will be called on redirects
49
+ # :callback - A callable used on redirects
58
50
  # with the old and new envs
59
51
  # :cookies - An Array of Strings (e.g.
60
52
  # ['cookie1', 'cookie2']) to choose
@@ -78,7 +70,7 @@ module FaradayMiddleware
78
70
  private
79
71
 
80
72
  def convert_to_get?(response)
81
- ![:head, :options].include?(response.env[:method]) &&
73
+ !%i[head options].include?(response.env[:method]) &&
82
74
  @convert_to_get.include?(response.status)
83
75
  end
84
76
 
@@ -89,8 +81,9 @@ module FaradayMiddleware
89
81
  response.on_complete do |response_env|
90
82
  if follow_redirect?(response_env, response)
91
83
  raise RedirectLimitReached, response if follows.zero?
84
+
92
85
  new_request_env = update_env(response_env.dup, request_body, response)
93
- callback.call(response_env, new_request_env) if callback
86
+ callback&.call(response_env, new_request_env)
94
87
  response = perform_with_redirection(new_request_env, follows - 1)
95
88
  end
96
89
  end
@@ -102,6 +95,8 @@ module FaradayMiddleware
102
95
  redirect_to_url = safe_escape(response['location'] || '')
103
96
  env[:url] += redirect_to_url
104
97
 
98
+ ENV_TO_CLEAR.each { |key| env.delete key }
99
+
105
100
  if convert_to_get?(response)
106
101
  env[:method] = :get
107
102
  env[:body] = nil
@@ -111,14 +106,12 @@ module FaradayMiddleware
111
106
 
112
107
  clear_authorization_header(env, redirect_from_url, redirect_to_url)
113
108
 
114
- ENV_TO_CLEAR.each {|key| env.delete key }
115
-
116
109
  env
117
110
  end
118
111
 
119
112
  def follow_redirect?(env, response)
120
- ALLOWED_METHODS.include? env[:method] and
121
- REDIRECT_CODES.include? response.status
113
+ ALLOWED_METHODS.include?(env[:method]) &&
114
+ REDIRECT_CODES.include?(response.status)
122
115
  end
123
116
 
124
117
  def follow_limit
@@ -139,9 +132,9 @@ module FaradayMiddleware
139
132
  # risk double-escaping.
140
133
  def safe_escape(uri)
141
134
  uri = uri.split('#')[0] # we want to remove the fragment if present
142
- uri.to_s.gsub(URI_UNSAFE) { |match|
135
+ uri.to_s.gsub(URI_UNSAFE) do |match|
143
136
  '%' + match.unpack('H2' * match.bytesize).join('%').upcase
144
- }
137
+ end
145
138
  end
146
139
 
147
140
  def clear_authorization_header(env, from_url, to_url)
@@ -157,7 +150,8 @@ module FaradayMiddleware
157
150
  from_uri = URI.parse(from_url)
158
151
  to_uri = URI.parse(to_url)
159
152
 
160
- [from_uri.scheme, from_uri.host, from_uri.port] == [to_uri.scheme, to_uri.host, to_uri.port]
153
+ [from_uri.scheme, from_uri.host, from_uri.port] ==
154
+ [to_uri.scheme, to_uri.host, to_uri.port]
161
155
  end
162
156
  end
163
157
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
 
3
5
  module FaradayMiddleware
@@ -1,10 +1,13 @@
1
- require "time"
2
- require "faraday"
1
+ # frozen_string_literal: true
2
+
3
+ require 'time'
4
+ require 'faraday'
3
5
 
4
6
  module FaradayMiddleware
5
7
  # Parse dates from response body
6
8
  class ParseDates < ::Faraday::Response::Middleware
7
- ISO_DATE_FORMAT = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|((\+|-)\d{2}:?\d{2}))\Z/m
9
+ ISO_DATE_FORMAT = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?
10
+ (Z|((\+|-)\d{2}:?\d{2}))\Z/xm.freeze
8
11
 
9
12
  def initialize(app, options = {})
10
13
  @regexp = options[:match] || ISO_DATE_FORMAT
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday_middleware/response_middleware'
2
4
 
3
5
  module FaradayMiddleware
@@ -18,7 +20,7 @@ module FaradayMiddleware
18
20
  # This is to fix responses from certain API providers that insist on serving
19
21
  # JSON with wrong MIME-types such as "text/javascript".
20
22
  class MimeTypeFix < ResponseMiddleware
21
- MIME_TYPE = 'application/json'.freeze
23
+ MIME_TYPE = 'application/json'
22
24
 
23
25
  def process_response(env)
24
26
  old_type = env[:response_headers][CONTENT_TYPE].to_s
@@ -27,19 +29,17 @@ module FaradayMiddleware
27
29
  env[:response_headers][CONTENT_TYPE] = new_type
28
30
  end
29
31
 
30
- BRACKETS = %w- [ { -
31
- WHITESPACE = [ " ", "\n", "\r", "\t" ]
32
+ BRACKETS = %w-[ {-.freeze
33
+ WHITESPACE = [' ', "\n", "\r", "\t"].freeze
32
34
 
33
35
  def parse_response?(env)
34
- super and BRACKETS.include? first_char(env[:body])
36
+ super && BRACKETS.include?(first_char(env[:body]))
35
37
  end
36
38
 
37
39
  def first_char(body)
38
40
  idx = -1
39
- begin
40
- char = body[idx += 1]
41
- char = char.chr if char
42
- end while char and WHITESPACE.include? char
41
+ char = body[idx += 1]
42
+ char = body[idx += 1] while char && WHITESPACE.include?(char)
43
43
  char
44
44
  end
45
45
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday_middleware/response_middleware'
2
4
 
3
5
  module FaradayMiddleware
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday_middleware/response_middleware'
2
4
 
3
5
  module FaradayMiddleware
@@ -1,13 +1,16 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday_middleware/response_middleware'
2
4
 
3
5
  module FaradayMiddleware
4
6
  # Public: Parse response bodies as YAML.
5
7
  #
6
- # Warning: This is not backwards compatible with versions of this middleware prior to
7
- # faraday_middleware v0.12 - prior to this version, we used YAML.load rather than
8
- # YAMl.safe_load, which exposes serious remote code execution risks - see
9
- # https://github.com/ruby/psych/issues/119 for details. If you're sure you can trust
10
- # YAML you're passing, you can set up an unsafe version of this middleware as follows:
8
+ # Warning: This is not backwards compatible with versions of this middleware
9
+ # prior to faraday_middleware v0.12 - prior to this version, we used
10
+ # YAML.load rather than YAMl.safe_load, which exposes serious remote code
11
+ # execution risks - see https://github.com/ruby/psych/issues/119 for details.
12
+ # If you're sure you can trust YAML you're passing, you can set up an unsafe
13
+ # version of this middleware like this:
11
14
  #
12
15
  # class UnsafelyParseYaml < FaradayMiddleware::ResponseMiddleware
13
16
  # dependency do
@@ -27,11 +30,7 @@ module FaradayMiddleware
27
30
  dependency 'safe_yaml/load'
28
31
 
29
32
  define_parser do |body, parser_options|
30
- if SafeYAML::YAML_ENGINE == 'psych'
31
- SafeYAML.load(body, nil, parser_options || {})
32
- else
33
- SafeYAML.load(body, parser_options || {})
34
- end
33
+ SafeYAML.load(body, nil, parser_options || {})
35
34
  end
36
35
  end
37
36
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday_middleware/response/mashify'
2
4
 
3
5
  module FaradayMiddleware
@@ -1,9 +1,12 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'faraday'
2
4
 
5
+ # Main FaradayMiddleware module.
3
6
  module FaradayMiddleware
4
7
  # Internal: The base class for middleware that parses responses.
5
8
  class ResponseMiddleware < Faraday::Middleware
6
- CONTENT_TYPE = 'Content-Type'.freeze
9
+ CONTENT_TYPE = 'Content-Type'
7
10
 
8
11
  class << self
9
12
  attr_accessor :parser
@@ -11,13 +14,15 @@ module FaradayMiddleware
11
14
 
12
15
  # Store a Proc that receives the body and returns the parsed result.
13
16
  def self.define_parser(parser = nil, &block)
14
- @parser = parser || block || raise(ArgumentError, 'Define parser with a block')
17
+ @parser = parser ||
18
+ block ||
19
+ raise(ArgumentError, 'Define parser with a block')
15
20
  end
16
21
 
17
22
  def self.inherited(subclass)
18
23
  super
19
- subclass.load_error = self.load_error if subclass.respond_to? :load_error=
20
- subclass.parser = self.parser
24
+ subclass.load_error = load_error if subclass.respond_to? :load_error=
25
+ subclass.parser = parser
21
26
  end
22
27
 
23
28
  def initialize(app = nil, options = {})
@@ -29,7 +34,7 @@ module FaradayMiddleware
29
34
 
30
35
  def call(environment)
31
36
  @app.call(environment).on_complete do |env|
32
- if process_response_type?(response_type(env)) and parse_response?(env)
37
+ if process_response_type?(response_type(env)) && parse_response?(env)
33
38
  process_response(env)
34
39
  end
35
40
  end
@@ -38,8 +43,8 @@ module FaradayMiddleware
38
43
  def process_response(env)
39
44
  env[:raw_body] = env[:body] if preserve_raw?(env)
40
45
  env[:body] = parse(env[:body])
41
- rescue Faraday::Error::ParsingError => err
42
- raise Faraday::Error::ParsingError.new(err, env[:response])
46
+ rescue Faraday::ParsingError => e
47
+ raise Faraday::ParsingError.new(e, env[:response])
43
48
  end
44
49
 
45
50
  # Parse the response body.
@@ -49,9 +54,11 @@ module FaradayMiddleware
49
54
  if self.class.parser
50
55
  begin
51
56
  self.class.parser.call(body, @parser_options)
52
- rescue StandardError, SyntaxError => err
53
- raise err if err.is_a? SyntaxError and err.class.name != 'Psych::SyntaxError'
54
- raise Faraday::Error::ParsingError, err
57
+ rescue StandardError, SyntaxError => e
58
+ raise e if e.is_a?(SyntaxError) &&
59
+ e.class.name != 'Psych::SyntaxError'
60
+
61
+ raise Faraday::ParsingError, e
55
62
  end
56
63
  else
57
64
  body
@@ -65,9 +72,9 @@ module FaradayMiddleware
65
72
  end
66
73
 
67
74
  def process_response_type?(type)
68
- @content_types.empty? or @content_types.any? { |pattern|
75
+ @content_types.empty? || @content_types.any? do |pattern|
69
76
  pattern.is_a?(Regexp) ? type =~ pattern : type == pattern
70
- }
77
+ end
71
78
  end
72
79
 
73
80
  def parse_response?(env)
@@ -84,17 +91,18 @@ module FaradayMiddleware
84
91
  attr_accessor :preserve_raw
85
92
 
86
93
  def to_hash
87
- super.update(:preserve_raw => preserve_raw)
94
+ super.update(preserve_raw: preserve_raw)
88
95
  end
89
96
 
90
97
  def each
91
98
  return to_enum(:each) unless block_given?
99
+
92
100
  super
93
101
  yield :preserve_raw, preserve_raw
94
102
  end
95
103
 
96
104
  def fetch(key, *args)
97
- if :preserve_raw == key
105
+ if key == :preserve_raw
98
106
  value = __send__(key)
99
107
  value.nil? ? args.fetch(0) : value
100
108
  else
@@ -105,9 +113,9 @@ module FaradayMiddleware
105
113
 
106
114
  if defined?(Faraday::RequestOptions)
107
115
  begin
108
- Faraday::RequestOptions.from(:preserve_raw => true)
116
+ Faraday::RequestOptions.from(preserve_raw: true)
109
117
  rescue NoMethodError
110
- Faraday::RequestOptions.send(:include, OptionsExtension)
118
+ Faraday::RequestOptions.include OptionsExtension
111
119
  end
112
120
  end
113
121
  end
@@ -1,3 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Main FaradayMiddleware module.
1
4
  module FaradayMiddleware
2
- VERSION = '0.14.0' unless defined?(FaradayMiddleware::VERSION)
5
+ VERSION = '1.0.0.rc1' unless defined?(FaradayMiddleware::VERSION)
3
6
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: faraday_middleware
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.14.0
4
+ version: 1.0.0.rc1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Erik Michaels-Ober
@@ -9,26 +9,20 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2020-01-19 00:00:00.000000000 Z
12
+ date: 2020-02-28 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: faraday
16
16
  requirement: !ruby/object:Gem::Requirement
17
17
  requirements:
18
- - - ">="
19
- - !ruby/object:Gem::Version
20
- version: 0.7.4
21
- - - "<"
18
+ - - "~>"
22
19
  - !ruby/object:Gem::Version
23
20
  version: '1.0'
24
21
  type: :runtime
25
22
  prerelease: false
26
23
  version_requirements: !ruby/object:Gem::Requirement
27
24
  requirements:
28
- - - ">="
29
- - !ruby/object:Gem::Version
30
- version: 0.7.4
31
- - - "<"
25
+ - - "~>"
32
26
  - !ruby/object:Gem::Version
33
27
  version: '1.0'
34
28
  description:
@@ -46,6 +40,7 @@ files:
46
40
  - lib/faraday_middleware/gzip.rb
47
41
  - lib/faraday_middleware/instrumentation.rb
48
42
  - lib/faraday_middleware/rack_compatible.rb
43
+ - lib/faraday_middleware/redirect_limit_reached.rb
49
44
  - lib/faraday_middleware/request/encode_json.rb
50
45
  - lib/faraday_middleware/request/method_override.rb
51
46
  - lib/faraday_middleware/request/oauth.rb
@@ -74,12 +69,12 @@ required_ruby_version: !ruby/object:Gem::Requirement
74
69
  requirements:
75
70
  - - ">="
76
71
  - !ruby/object:Gem::Version
77
- version: '0'
72
+ version: '2.3'
78
73
  required_rubygems_version: !ruby/object:Gem::Requirement
79
74
  requirements:
80
- - - ">="
75
+ - - ">"
81
76
  - !ruby/object:Gem::Version
82
- version: '0'
77
+ version: 1.3.1
83
78
  requirements: []
84
79
  rubygems_version: 3.0.3
85
80
  signing_key: