-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathapi_client_faraday_partial.mustache
200 lines (175 loc) · 6.99 KB
/
api_client_faraday_partial.mustache
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# Call an API with given options.
#
# @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
# the data deserialized from response body (could be nil), response status code and response headers.
def call_api(http_method, path, opts = {})
stream = nil
begin
response = connection(opts).public_send(http_method.to_sym.downcase) do |req|
request = build_request(http_method, path, req, opts)
stream = download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary'
end
if config.debugging
config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
end
unless response.success?
if response.status == 0 && response.respond_to?(:return_message)
# Errors from libcurl will be made visible here
fail ApiError.new(code: 0,
message: response.return_message)
else
fail ApiError.new(code: response.status,
response_headers: response.headers,
response_body: response.body),
response.reason_phrase
end
end
rescue Faraday::TimeoutError
fail ApiError.new('Connection timed out')
rescue Faraday::ConnectionFailed
fail ApiError.new('Connection failed')
end
if opts[:return_type] == 'File' || opts[:return_type] == 'Binary'
data = deserialize_file(response, stream)
elsif opts[:return_type]
data = deserialize(response, opts[:return_type])
else
data = nil
end
return data, response.status, response.headers
end
# Builds the HTTP request
#
# @param [String] http_method HTTP method/verb (e.g. POST)
# @param [String] path URL path (e.g. /account/new)
# @option opts [Hash] :header_params Header parameters
# @option opts [Hash] :query_params Query parameters
# @option opts [Hash] :form_params Query parameters
# @option opts [Object] :body HTTP body (JSON/XML)
# @return [Faraday::Request] A Faraday Request
def build_request(http_method, path, request, opts = {})
url = build_request_url(path, opts)
http_method = http_method.to_sym.downcase
header_params = @default_headers.merge(opts[:header_params] || {})
query_params = opts[:query_params] || {}
form_params = opts[:form_params] || {}
update_params_for_auth! header_params, query_params, opts[:auth_names]
if [:post, :patch, :put, :delete].include?(http_method)
req_body = build_request_body(header_params, form_params, opts[:body])
if config.debugging
config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
end
end
request.headers = header_params
request.body = req_body
# Overload default options only if provided
request.options.params_encoder = config.params_encoder if config.params_encoder
request.options.timeout = config.timeout if config.timeout
request.url url
request.params = query_params
request
end
# Builds the HTTP request body
#
# @param [Hash] header_params Header parameters
# @param [Hash] form_params Query parameters
# @param [Object] body HTTP body (JSON/XML)
# @return [String] HTTP body data in the form of string
def build_request_body(header_params, form_params, body)
# http form
if header_params['Content-Type'] == 'application/x-www-form-urlencoded'
data = URI.encode_www_form(form_params)
elsif header_params['Content-Type'] == 'multipart/form-data'
data = {}
form_params.each do |key, value|
case value
when ::File, ::Tempfile
data[key] = Faraday::FilePart.new(value.path, Marcel::MimeType.for(Pathname.new(value.path)))
when ::Array, nil
# let Faraday handle Array and nil parameters
data[key] = value
else
data[key] = value.to_s
end
end
elsif body
data = body.is_a?(String) ? body : body.to_json
else
data = nil
end
data
end
def download_file(request)
stream = []
# handle streaming Responses
request.options.on_data = Proc.new do |chunk, overall_received_bytes|
stream << chunk
end
stream
end
def deserialize_file(response, stream)
body = response.body
encoding = body.encoding
# reconstruct content
content = stream.join
content = content.unpack('m').join if response.headers['Content-Transfer-Encoding'] == 'binary'
content = content.force_encoding(encoding)
# return byte stream
return content if @config.return_binary_data == true
# return file instead of binary data
content_disposition = response.headers['Content-Disposition']
if content_disposition && content_disposition =~ /filename=/i
filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
prefix = sanitize_filename(filename)
else
prefix = 'download-'
end
prefix = prefix + '-' unless prefix.end_with?('-')
tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
tempfile.write(content)
tempfile.close
config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
"with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
"will be deleted automatically with GC. It's also recommended to delete the temp file "\
"explicitly with `tempfile.delete`"
tempfile
end
def connection(opts)
opts[:header_params]['Content-Type'] == 'multipart/form-data' ? connection_multipart : connection_regular
end
def connection_multipart
@connection_multipart ||= build_connection do |conn|
conn.request :multipart
conn.request :url_encoded
end
end
def connection_regular
@connection_regular ||= build_connection
end
def build_connection
Faraday.new(url: config.base_url, ssl: ssl_options, proxy: config.proxy) do |conn|
basic_auth(conn)
config.configure_middleware(conn)
yield(conn) if block_given?
conn.adapter(Faraday.default_adapter)
config.configure_connection(conn)
end
end
def ssl_options
{
ca_file: config.ssl_ca_file,
verify: config.ssl_verify,
verify_mode: config.ssl_verify_mode,
client_cert: config.ssl_client_cert,
client_key: config.ssl_client_key
}
end
def basic_auth(conn)
if config.username && config.password
if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new('2.0')
conn.request(:authorization, :basic, config.username, config.password)
else
conn.request(:basic_auth, config.username, config.password)
end
end
end