This repository has been archived by the owner on Oct 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
response_middleware.rb
70 lines (60 loc) · 1.8 KB
/
response_middleware.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
module FaradayStack
# A base class for middleware that parses responses
class ResponseMiddleware < Faraday::Response::Middleware
CONTENT_TYPE = 'Content-Type'.freeze
# Executes a block which should try to require and reference dependent libraries
def self.dependency
yield
rescue LoadError, NameError => error
self.load_error = error
end
class << self
attr_accessor :parser
end
# Stores a block that receives the body and should return a parsed result
def self.define_parser(&block)
@parser = block
end
def self.inherited(subclass)
super
subclass.load_error = self.load_error
subclass.parser = self.parser
end
def initialize(app = nil, options = {})
super(app)
@content_types = Array(options[:content_type])
end
# Override this to modify the environment after the response has finished.
def on_complete(env)
if process_response_type?(response_type(env)) and parse_response?(env)
env[:body] = parse(env[:body])
end
end
# Parses the response body and returns the result.
# Instead of overriding this method, consider using `define_parser`
def parse(body)
if self.class.parser
begin
self.class.parser.call(body)
rescue
raise Faraday::Error::ParsingError, $!
end
else
body
end
end
def response_type(env)
type = env[:response_headers][CONTENT_TYPE].to_s
type = type.split(';', 2).first if type.index(';')
type
end
def process_response_type?(type)
@content_types.empty? or @content_types.any? { |pattern|
Regexp === pattern ? type =~ pattern : type == pattern
}
end
def parse_response?(env)
env[:body].respond_to? :to_str
end
end
end