minato_ruby_api_client 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +23 -23
  3. data/Dockerfile +1 -1
  4. data/Gemfile +17 -17
  5. data/Gemfile.lock +402 -398
  6. data/README.md +54 -54
  7. data/Rakefile +10 -10
  8. data/compose.yml +11 -11
  9. data/lib/minato_ruby_api_client/api_client.rb +398 -389
  10. data/lib/minato_ruby_api_client/api_error.rb +16 -16
  11. data/lib/minato_ruby_api_client/configuration.rb +247 -247
  12. data/lib/minato_ruby_api_client/version.rb +3 -3
  13. data/lib/minato_ruby_api_client.rb +24 -24
  14. data/minato_ruby_api_client.gemspec +35 -35
  15. data/spec/api_client_spec.rb +42 -0
  16. data/spec/configuration_spec.rb +204 -204
  17. data/spec/minato_ruby_api_client_spec.rb +17 -17
  18. data/spec/spec_helper.rb +105 -105
  19. metadata +7 -40
  20. data/coverage/.last_run.json +0 -5
  21. data/coverage/.resultset.json +0 -1248
  22. data/coverage/.resultset.json.lock +0 -0
  23. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_asc.png +0 -0
  24. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_asc_disabled.png +0 -0
  25. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_both.png +0 -0
  26. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_desc.png +0 -0
  27. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_desc_disabled.png +0 -0
  28. data/coverage/assets/0.12.3/application.css +0 -1
  29. data/coverage/assets/0.12.3/application.js +0 -7
  30. data/coverage/assets/0.12.3/colorbox/border.png +0 -0
  31. data/coverage/assets/0.12.3/colorbox/controls.png +0 -0
  32. data/coverage/assets/0.12.3/colorbox/loading.gif +0 -0
  33. data/coverage/assets/0.12.3/colorbox/loading_background.png +0 -0
  34. data/coverage/assets/0.12.3/favicon_green.png +0 -0
  35. data/coverage/assets/0.12.3/favicon_red.png +0 -0
  36. data/coverage/assets/0.12.3/favicon_yellow.png +0 -0
  37. data/coverage/assets/0.12.3/images/ui-bg_flat_0_aaaaaa_40x100.png +0 -0
  38. data/coverage/assets/0.12.3/images/ui-bg_flat_75_ffffff_40x100.png +0 -0
  39. data/coverage/assets/0.12.3/images/ui-bg_glass_55_fbf9ee_1x400.png +0 -0
  40. data/coverage/assets/0.12.3/images/ui-bg_glass_65_ffffff_1x400.png +0 -0
  41. data/coverage/assets/0.12.3/images/ui-bg_glass_75_dadada_1x400.png +0 -0
  42. data/coverage/assets/0.12.3/images/ui-bg_glass_75_e6e6e6_1x400.png +0 -0
  43. data/coverage/assets/0.12.3/images/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  44. data/coverage/assets/0.12.3/images/ui-bg_highlight-soft_75_cccccc_1x100.png +0 -0
  45. data/coverage/assets/0.12.3/images/ui-icons_222222_256x240.png +0 -0
  46. data/coverage/assets/0.12.3/images/ui-icons_2e83ff_256x240.png +0 -0
  47. data/coverage/assets/0.12.3/images/ui-icons_454545_256x240.png +0 -0
  48. data/coverage/assets/0.12.3/images/ui-icons_888888_256x240.png +0 -0
  49. data/coverage/assets/0.12.3/images/ui-icons_cd0a0a_256x240.png +0 -0
  50. data/coverage/assets/0.12.3/loading.gif +0 -0
  51. data/coverage/assets/0.12.3/magnify.png +0 -0
  52. data/coverage/index.html +0 -13728
@@ -1,389 +1,398 @@
1
- require 'date'
2
- require 'json'
3
- require 'logger'
4
- require 'tempfile'
5
- require 'time'
6
- require 'faraday'
7
- require 'minato/trace'
8
- require 'ostruct'
9
-
10
- module MinatoRubyApiClient
11
- class ApiClient
12
- # The Configuration object holding settings to be used in the API client.
13
- attr_accessor :config
14
-
15
- # Defines the headers to be used in HTTP requests of all API calls by default.
16
- #
17
- # @return [Hash]
18
- attr_accessor :default_headers
19
-
20
- # Initializes the ApiClient
21
- # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
22
- def initialize(config = Configuration.default)
23
- @config = config
24
- @user_agent = config.user_agent
25
- @default_headers = {
26
- 'Content-Type' => 'application/json',
27
- 'User-Agent' => @user_agent
28
- }
29
-
30
- if defined?(Rails) && Rails.env.production? && Minato::Trace.enabled?
31
- @config.use(Minato::Trace::Middleware::DistributedTraceContext)
32
- end
33
- end
34
-
35
- def self.default
36
- @@default ||= ApiClient.new
37
- end
38
-
39
- # Call an API with given options.
40
- #
41
- # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
42
- # the data deserialized from response body (could be nil), response status code and response headers.
43
- def call_api(http_method, path, opts = {})
44
- ssl_options = {
45
- :ca_file => @config.ssl_ca_file,
46
- :verify => @config.ssl_verify,
47
- :verify_mode => @config.ssl_verify_mode,
48
- :client_cert => @config.ssl_client_cert,
49
- :client_key => @config.ssl_client_key
50
- }
51
-
52
- connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn|
53
- @config.configure_middleware(conn)
54
- if opts[:header_params] && opts[:header_params]["Content-Type"] == "multipart/form-data"
55
- conn.request :multipart
56
- conn.request :url_encoded
57
- end
58
- conn.adapter(Faraday.default_adapter)
59
- end
60
-
61
- request = nil
62
-
63
- begin
64
- response = connection.public_send(http_method.to_sym.downcase) do |req|
65
- request = req
66
- build_request(http_method, path, req, opts)
67
- end
68
-
69
- @config.logger.info({ 'message' => "Receive response from #{response.env.url}",
70
- 'http_response' => response.to_hash })
71
-
72
- unless response.success?
73
- error = self.class.module_parent::ApiError.new(:status_code => response.status,
74
- :res => response, :req => request)
75
- error.caused_by = response.reason_phrase
76
-
77
- fail error
78
- end
79
- rescue Faraday::TimeoutError => e
80
- error = self.class.module_parent::ApiError.new(req: request, res: response, status_code: 408)
81
- error.caused_by = e
82
- fail error
83
- end
84
-
85
- if opts[:return_type]
86
- data = deserialize(response, opts[:return_type])
87
- else
88
- data = nil
89
- end
90
- return data, response.status, response.headers
91
- end
92
-
93
- # Builds the HTTP request
94
- #
95
- # @param [String] http_method HTTP method/verb (e.g. POST)
96
- # @param [String] path URL path (e.g. /account/new)
97
- # @option opts [Hash] :header_params Header parameters
98
- # @option opts [Hash] :query_params Query parameters
99
- # @option opts [Hash] :form_params Query parameters
100
- # @option opts [Object] :body HTTP body (JSON/XML)
101
- # @return [Typhoeus::Request] A Typhoeus Request
102
- def build_request(http_method, path, request, opts = {})
103
- url = build_request_url(path)
104
- http_method = http_method.to_sym.downcase
105
-
106
- header_params = @default_headers.merge(opts[:header_params] || {})
107
- query_params = opts[:query_params] || {}
108
- form_params = opts[:form_params] || {}
109
-
110
- update_params_for_auth! header_params, query_params, opts[:auth_names]
111
-
112
- req_opts = {
113
- :params_encoding => @config.params_encoding,
114
- :timeout => @config.timeout,
115
- :verbose => @config.debugging
116
- }
117
-
118
- if [:post, :patch, :put, :delete].include?(http_method)
119
- req_body = build_request_body(header_params, form_params, opts[:body])
120
- end
121
- request.headers = header_params
122
- request.body = req_body
123
- request.options = OpenStruct.new(req_opts)
124
- request.url url
125
- request.params = query_params
126
- download_file(request) if opts[:return_type] == 'File'
127
-
128
- @config.logger.info({ 'message' => "Starting request to #{url}",
129
- 'http_request' => request.to_h })
130
-
131
- request
132
- end
133
-
134
- # Builds the HTTP request body
135
- #
136
- # @param [Hash] header_params Header parameters
137
- # @param [Hash] form_params Query parameters
138
- # @param [Object] body HTTP body (JSON/XML)
139
- # @return [String] HTTP body data in the form of string
140
- def build_request_body(header_params, form_params, body)
141
- # http form
142
- if header_params['Content-Type'] == 'application/x-www-form-urlencoded'
143
- data = URI.encode_www_form(form_params)
144
- elsif header_params['Content-Type'] == 'multipart/form-data'
145
- data = {}
146
- form_params.each do |key, value|
147
- case value
148
- when ActionDispatch::Http::UploadedFile
149
- # TODO hardcode to application/octet-stream, need better way to detect content type
150
- data[key] = Faraday::UploadIO.new(value.path, value.content_type, value.original_filename)
151
- when ::File, ::Tempfile
152
- # TODO hardcode to application/octet-stream, need better way to detect content type
153
- data[key] = Faraday::UploadIO.new(value.path, 'application/octet-stream', value.path)
154
- when ::Array, nil
155
- # let Faraday handle Array and nil parameters
156
- data[key] = value
157
- else
158
- data[key] = value.to_s
159
- end
160
- end
161
- elsif body
162
- data = body.is_a?(String) ? body : body.to_json
163
- else
164
- data = nil
165
- end
166
- data
167
- end
168
-
169
- def download_file(request)
170
- @stream = []
171
-
172
- # handle streaming Responses
173
- request.options.on_data = Proc.new do |chunk, overall_received_bytes|
174
- @stream << chunk
175
- end
176
- end
177
-
178
- # Check if the given MIME is a JSON MIME.
179
- # JSON MIME examples:
180
- # application/json
181
- # application/json; charset=UTF8
182
- # APPLICATION/JSON
183
- # */*
184
- # @param [String] mime MIME
185
- # @return [Boolean] True if the MIME is application/json
186
- def json_mime?(mime)
187
- (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
188
- end
189
-
190
- # Deserialize the response to the given return type.
191
- #
192
- # @param [Response] response HTTP response
193
- # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
194
- def deserialize(response, return_type)
195
- body = response.body
196
-
197
- # handle file downloading - return the File instance processed in request callbacks
198
- # note that response body is empty when the file is written in chunks in request on_body callback
199
- if return_type == 'File'
200
- content_disposition = response.headers['Content-Disposition']
201
- if content_disposition && content_disposition =~ /filename=/i
202
- filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
203
- prefix = sanitize_filename(filename)
204
- else
205
- prefix = 'download-'
206
- end
207
- prefix = prefix + '-' unless prefix.end_with?('-')
208
- encoding = body.encoding
209
- @tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
210
- @tempfile.write(@stream.join.force_encoding(encoding))
211
- @tempfile.close
212
- @config.logger.info "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\
213
- "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
214
- "will be deleted automatically with GC. It's also recommended to delete the temp file "\
215
- "explicitly with `tempfile.delete`"
216
- return @tempfile
217
- end
218
-
219
- return nil if body.nil? || body.empty?
220
-
221
- # return response body directly for String return type
222
- return body if return_type == 'String'
223
-
224
- # ensuring a default content type
225
- content_type = response.headers['Content-Type'] || 'application/json'
226
-
227
- fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
228
-
229
- begin
230
- data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
231
- rescue JSON::ParserError => e
232
- if %w(String Date Time).include?(return_type)
233
- data = body
234
- else
235
- raise e
236
- end
237
- end
238
-
239
- convert_to_type data, return_type
240
- end
241
-
242
- # Convert data to the given return type.
243
- # @param [Object] data Data to be converted
244
- # @param [String] return_type Return type
245
- # @return [Mixed] Data in a particular type
246
- def convert_to_type(data, return_type)
247
- return nil if data.nil?
248
- case return_type
249
- when 'String'
250
- data.to_s
251
- when 'Integer'
252
- data.to_i
253
- when 'Float'
254
- data.to_f
255
- when 'Boolean'
256
- data == true
257
- when 'Time'
258
- # parse date time (expecting ISO 8601 format)
259
- Time.parse data
260
- when 'Date'
261
- # parse date time (expecting ISO 8601 format)
262
- Date.parse data
263
- when 'Object'
264
- # generic object (usually a Hash), return directly
265
- data
266
- when /\AArray<(.+)>\z/
267
- # e.g. Array<Pet>
268
- sub_type = $1
269
- data.map { |item| convert_to_type(item, sub_type) }
270
- when /\AHash\<String, (.+)\>\z/
271
- # e.g. Hash<String, Integer>
272
- sub_type = $1
273
- {}.tap do |hash|
274
- data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
275
- end
276
- else
277
- # models (e.g. Pet) or oneOf
278
- klass = self.class.module_parent.const_get(return_type)
279
- klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
280
- end
281
- end
282
-
283
- # Sanitize filename by removing path.
284
- # e.g. ../../sun.gif becomes sun.gif
285
- #
286
- # @param [String] filename the filename to be sanitized
287
- # @return [String] the sanitized filename
288
- def sanitize_filename(filename)
289
- filename.gsub(/.*[\/\\]/, '')
290
- end
291
-
292
- def build_request_url(path)
293
- # Add leading and trailing slashes to path
294
- path = "/#{path}".gsub(/\/+/, '/')
295
- @config.base_url + path
296
- end
297
-
298
- # Update header and query params based on authentication settings.
299
- #
300
- # @param [Hash] header_params Header parameters
301
- # @param [Hash] query_params Query parameters
302
- # @param [String] auth_names Authentication scheme name
303
- def update_params_for_auth!(header_params, query_params, auth_names)
304
- Array(auth_names).each do |auth_name|
305
- auth_setting = @config.auth_settings[auth_name]
306
- next unless auth_setting
307
- case auth_setting[:in]
308
- when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
309
- when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
310
- else fail ArgumentError, 'Authentication token must be in `query` or `header`'
311
- end
312
- end
313
- end
314
-
315
- # Sets user agent in HTTP header
316
- #
317
- # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
318
- def user_agent=(user_agent)
319
- @user_agent = user_agent
320
- @default_headers['User-Agent'] = @user_agent
321
- end
322
-
323
- # Return Accept header based on an array of accepts provided.
324
- # @param [Array] accepts array for Accept
325
- # @return [String] the Accept header (e.g. application/json)
326
- def select_header_accept(accepts)
327
- return nil if accepts.nil? || accepts.empty?
328
- # use JSON when present, otherwise use all of the provided
329
- json_accept = accepts.find { |s| json_mime?(s) }
330
- json_accept || accepts.join(',')
331
- end
332
-
333
- # Return Content-Type header based on an array of content types provided.
334
- # @param [Array] content_types array for Content-Type
335
- # @return [String] the Content-Type header (e.g. application/json)
336
- def select_header_content_type(content_types)
337
- # return nil by default
338
- return if content_types.nil? || content_types.empty?
339
- # use JSON when present, otherwise use the first one
340
- json_content_type = content_types.find { |s| json_mime?(s) }
341
- json_content_type || content_types.first
342
- end
343
-
344
- # Convert object (array, hash, object, etc) to JSON string.
345
- # @param [Object] model object to be converted into JSON string
346
- # @return [String] JSON string representation of the object
347
- def object_to_http_body(model)
348
- return model if model.nil? || model.is_a?(String)
349
- local_body = nil
350
- if model.is_a?(Array)
351
- local_body = model.map { |m| object_to_hash(m) }
352
- else
353
- local_body = object_to_hash(model)
354
- end
355
- local_body.to_json
356
- end
357
-
358
- # Convert object(non-array) to hash.
359
- # @param [Object] obj object to be converted into JSON string
360
- # @return [String] JSON string representation of the object
361
- def object_to_hash(obj)
362
- if obj.respond_to?(:to_hash)
363
- obj.to_hash
364
- else
365
- obj
366
- end
367
- end
368
-
369
- # Build parameter value according to the given collection format.
370
- # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
371
- def build_collection_param(param, collection_format)
372
- case collection_format
373
- when :csv
374
- param.join(',')
375
- when :ssv
376
- param.join(' ')
377
- when :tsv
378
- param.join("\t")
379
- when :pipes
380
- param.join('|')
381
- when :multi
382
- # return the array directly as typhoeus will handle it as expected
383
- param
384
- else
385
- fail "unknown collection format: #{collection_format.inspect}"
386
- end
387
- end
388
- end
389
- end
1
+ require 'date'
2
+ require 'json'
3
+ require 'logger'
4
+ require 'tempfile'
5
+ require 'time'
6
+ require 'faraday'
7
+ require 'minato/trace'
8
+ require 'ostruct'
9
+
10
+ module MinatoRubyApiClient
11
+ class ApiClient
12
+ # The Configuration object holding settings to be used in the API client.
13
+ attr_accessor :config
14
+
15
+ # Defines the headers to be used in HTTP requests of all API calls by default.
16
+ #
17
+ # @return [Hash]
18
+ attr_accessor :default_headers
19
+
20
+ # Initializes the ApiClient
21
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
22
+ def initialize(config = Configuration.default)
23
+ @config = config
24
+ @user_agent = config.user_agent
25
+ @default_headers = {
26
+ 'Content-Type' => 'application/json',
27
+ 'User-Agent' => @user_agent
28
+ }
29
+
30
+ if defined?(Rails) && Rails.env.production? && Minato::Trace.enabled?
31
+ @config.use(Minato::Trace::Middleware::DistributedTraceContext)
32
+ end
33
+ end
34
+
35
+ def self.default
36
+ @@default ||= ApiClient.new
37
+ end
38
+
39
+ # Call an API with given options.
40
+ #
41
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
42
+ # the data deserialized from response body (could be nil), response status code and response headers.
43
+ def call_api(http_method, path, opts = {})
44
+ ssl_options = {
45
+ :ca_file => @config.ssl_ca_file,
46
+ :verify => @config.ssl_verify,
47
+ :verify_mode => @config.ssl_verify_mode,
48
+ :client_cert => @config.ssl_client_cert,
49
+ :client_key => @config.ssl_client_key
50
+ }
51
+
52
+ connection = Faraday.new(:url => config.base_url, :ssl => ssl_options) do |conn|
53
+ @config.configure_middleware(conn)
54
+ if opts[:header_params] && opts[:header_params]["Content-Type"] == "multipart/form-data"
55
+ conn.request :multipart
56
+ conn.request :url_encoded
57
+ end
58
+ conn.adapter(Faraday.default_adapter)
59
+ end
60
+
61
+ request = nil
62
+
63
+ begin
64
+ response = connection.public_send(http_method.to_sym.downcase) do |req|
65
+ request = req
66
+ build_request(http_method, path, req, opts)
67
+ end
68
+
69
+ log_response(response)
70
+
71
+ unless response.success?
72
+ error = self.class.module_parent::ApiError.new(:status_code => response.status,
73
+ :res => response, :req => request)
74
+ error.caused_by = response.reason_phrase
75
+
76
+ fail error
77
+ end
78
+ rescue Faraday::TimeoutError => e
79
+ error = self.class.module_parent::ApiError.new(req: request, res: response, status_code: 408)
80
+ error.caused_by = e
81
+ fail error
82
+ end
83
+
84
+ if opts[:return_type]
85
+ data = deserialize(response, opts[:return_type])
86
+ else
87
+ data = nil
88
+ end
89
+ return data, response.status, response.headers
90
+ end
91
+
92
+ # Builds the HTTP request
93
+ #
94
+ # @param [String] http_method HTTP method/verb (e.g. POST)
95
+ # @param [String] path URL path (e.g. /account/new)
96
+ # @option opts [Hash] :header_params Header parameters
97
+ # @option opts [Hash] :query_params Query parameters
98
+ # @option opts [Hash] :form_params Query parameters
99
+ # @option opts [Object] :body HTTP body (JSON/XML)
100
+ # @return [Typhoeus::Request] A Typhoeus Request
101
+ def build_request(http_method, path, request, opts = {})
102
+ url = build_request_url(path)
103
+ http_method = http_method.to_sym.downcase
104
+
105
+ header_params = @default_headers.merge(opts[:header_params] || {})
106
+ query_params = opts[:query_params] || {}
107
+ form_params = opts[:form_params] || {}
108
+
109
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
110
+
111
+ req_opts = {
112
+ :params_encoding => @config.params_encoding,
113
+ :timeout => @config.timeout,
114
+ :verbose => @config.debugging
115
+ }
116
+
117
+ if [:post, :patch, :put, :delete].include?(http_method)
118
+ req_body = build_request_body(header_params, form_params, opts[:body])
119
+ end
120
+ request.headers = header_params
121
+ request.body = req_body
122
+ request.options = OpenStruct.new(req_opts)
123
+ request.url url
124
+ request.params = query_params
125
+ download_file(request) if opts[:return_type] == 'File'
126
+
127
+ @config.logger.info({ 'message' => "Starting request to #{url}",
128
+ 'http_request' => request.to_h })
129
+
130
+ request
131
+ end
132
+
133
+ # Builds the HTTP request body
134
+ #
135
+ # @param [Hash] header_params Header parameters
136
+ # @param [Hash] form_params Query parameters
137
+ # @param [Object] body HTTP body (JSON/XML)
138
+ # @return [String] HTTP body data in the form of string
139
+ def build_request_body(header_params, form_params, body)
140
+ # http form
141
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded'
142
+ data = URI.encode_www_form(form_params)
143
+ elsif header_params['Content-Type'] == 'multipart/form-data'
144
+ data = {}
145
+ form_params.each do |key, value|
146
+ case value
147
+ when ActionDispatch::Http::UploadedFile
148
+ # TODO hardcode to application/octet-stream, need better way to detect content type
149
+ data[key] = Faraday::UploadIO.new(value.path, value.content_type, value.original_filename)
150
+ when ::File, ::Tempfile
151
+ # TODO hardcode to application/octet-stream, need better way to detect content type
152
+ data[key] = Faraday::UploadIO.new(value.path, 'application/octet-stream', value.path)
153
+ when ::Array, nil
154
+ # let Faraday handle Array and nil parameters
155
+ data[key] = value
156
+ else
157
+ data[key] = value.to_s
158
+ end
159
+ end
160
+ elsif body
161
+ data = body.is_a?(String) ? body : body.to_json
162
+ else
163
+ data = nil
164
+ end
165
+ data
166
+ end
167
+
168
+ def download_file(request)
169
+ @stream = []
170
+
171
+ # handle streaming Responses
172
+ request.options.on_data = Proc.new do |chunk, overall_received_bytes|
173
+ @stream << chunk
174
+ end
175
+ end
176
+
177
+ # Check if the given MIME is a JSON MIME.
178
+ # JSON MIME examples:
179
+ # application/json
180
+ # application/json; charset=UTF8
181
+ # APPLICATION/JSON
182
+ # */*
183
+ # @param [String] mime MIME
184
+ # @return [Boolean] True if the MIME is application/json
185
+ def json_mime?(mime)
186
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
187
+ end
188
+
189
+ # Deserialize the response to the given return type.
190
+ #
191
+ # @param [Response] response HTTP response
192
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
193
+ def deserialize(response, return_type)
194
+ body = response.body
195
+
196
+ # handle file downloading - return the File instance processed in request callbacks
197
+ # note that response body is empty when the file is written in chunks in request on_body callback
198
+ if return_type == 'File'
199
+ content_disposition = response.headers['Content-Disposition']
200
+ if content_disposition && content_disposition =~ /filename=/i
201
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
202
+ prefix = sanitize_filename(filename)
203
+ else
204
+ prefix = 'download-'
205
+ end
206
+ prefix = prefix + '-' unless prefix.end_with?('-')
207
+ encoding = body.encoding
208
+ @tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
209
+ @tempfile.write(@stream.join.force_encoding(encoding))
210
+ @tempfile.close
211
+ @config.logger.info "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\
212
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
213
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
214
+ "explicitly with `tempfile.delete`"
215
+ return @tempfile
216
+ end
217
+
218
+ return nil if body.nil? || body.empty?
219
+
220
+ # return response body directly for String return type
221
+ return body if return_type == 'String'
222
+
223
+ # ensuring a default content type
224
+ content_type = response.headers['Content-Type'] || 'application/json'
225
+
226
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
227
+
228
+ begin
229
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
230
+ rescue JSON::ParserError => e
231
+ if %w(String Date Time).include?(return_type)
232
+ data = body
233
+ else
234
+ raise e
235
+ end
236
+ end
237
+
238
+ convert_to_type data, return_type
239
+ end
240
+
241
+ # Convert data to the given return type.
242
+ # @param [Object] data Data to be converted
243
+ # @param [String] return_type Return type
244
+ # @return [Mixed] Data in a particular type
245
+ def convert_to_type(data, return_type)
246
+ return nil if data.nil?
247
+ case return_type
248
+ when 'String'
249
+ data.to_s
250
+ when 'Integer'
251
+ data.to_i
252
+ when 'Float'
253
+ data.to_f
254
+ when 'Boolean'
255
+ data == true
256
+ when 'Time'
257
+ # parse date time (expecting ISO 8601 format)
258
+ Time.parse data
259
+ when 'Date'
260
+ # parse date time (expecting ISO 8601 format)
261
+ Date.parse data
262
+ when 'Object'
263
+ # generic object (usually a Hash), return directly
264
+ data
265
+ when /\AArray<(.+)>\z/
266
+ # e.g. Array<Pet>
267
+ sub_type = $1
268
+ data.map { |item| convert_to_type(item, sub_type) }
269
+ when /\AHash\<String, (.+)\>\z/
270
+ # e.g. Hash<String, Integer>
271
+ sub_type = $1
272
+ {}.tap do |hash|
273
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
274
+ end
275
+ else
276
+ # models (e.g. Pet) or oneOf
277
+ klass = self.class.module_parent.const_get(return_type)
278
+ klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
279
+ end
280
+ end
281
+
282
+ # Sanitize filename by removing path.
283
+ # e.g. ../../sun.gif becomes sun.gif
284
+ #
285
+ # @param [String] filename the filename to be sanitized
286
+ # @return [String] the sanitized filename
287
+ def sanitize_filename(filename)
288
+ filename.gsub(/.*[\/\\]/, '')
289
+ end
290
+
291
+ def build_request_url(path)
292
+ # Add leading and trailing slashes to path
293
+ path = "/#{path}".gsub(/\/+/, '/')
294
+ @config.base_url + path
295
+ end
296
+
297
+ # Update header and query params based on authentication settings.
298
+ #
299
+ # @param [Hash] header_params Header parameters
300
+ # @param [Hash] query_params Query parameters
301
+ # @param [String] auth_names Authentication scheme name
302
+ def update_params_for_auth!(header_params, query_params, auth_names)
303
+ Array(auth_names).each do |auth_name|
304
+ auth_setting = @config.auth_settings[auth_name]
305
+ next unless auth_setting
306
+ case auth_setting[:in]
307
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
308
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
309
+ else fail ArgumentError, 'Authentication token must be in `query` or `header`'
310
+ end
311
+ end
312
+ end
313
+
314
+ # Sets user agent in HTTP header
315
+ #
316
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
317
+ def user_agent=(user_agent)
318
+ @user_agent = user_agent
319
+ @default_headers['User-Agent'] = @user_agent
320
+ end
321
+
322
+ # Return Accept header based on an array of accepts provided.
323
+ # @param [Array] accepts array for Accept
324
+ # @return [String] the Accept header (e.g. application/json)
325
+ def select_header_accept(accepts)
326
+ return nil if accepts.nil? || accepts.empty?
327
+ # use JSON when present, otherwise use all of the provided
328
+ json_accept = accepts.find { |s| json_mime?(s) }
329
+ json_accept || accepts.join(',')
330
+ end
331
+
332
+ # Return Content-Type header based on an array of content types provided.
333
+ # @param [Array] content_types array for Content-Type
334
+ # @return [String] the Content-Type header (e.g. application/json)
335
+ def select_header_content_type(content_types)
336
+ # return nil by default
337
+ return if content_types.nil? || content_types.empty?
338
+ # use JSON when present, otherwise use the first one
339
+ json_content_type = content_types.find { |s| json_mime?(s) }
340
+ json_content_type || content_types.first
341
+ end
342
+
343
+ # Convert object (array, hash, object, etc) to JSON string.
344
+ # @param [Object] model object to be converted into JSON string
345
+ # @return [String] JSON string representation of the object
346
+ def object_to_http_body(model)
347
+ return model if model.nil? || model.is_a?(String)
348
+ local_body = nil
349
+ if model.is_a?(Array)
350
+ local_body = model.map { |m| object_to_hash(m) }
351
+ else
352
+ local_body = object_to_hash(model)
353
+ end
354
+ local_body.to_json
355
+ end
356
+
357
+ # Convert object(non-array) to hash.
358
+ # @param [Object] obj object to be converted into JSON string
359
+ # @return [String] JSON string representation of the object
360
+ def object_to_hash(obj)
361
+ if obj.respond_to?(:to_hash)
362
+ obj.to_hash
363
+ else
364
+ obj
365
+ end
366
+ end
367
+
368
+ # Build parameter value according to the given collection format.
369
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
370
+ def build_collection_param(param, collection_format)
371
+ case collection_format
372
+ when :csv
373
+ param.join(',')
374
+ when :ssv
375
+ param.join(' ')
376
+ when :tsv
377
+ param.join("\t")
378
+ when :pipes
379
+ param.join('|')
380
+ when :multi
381
+ # return the array directly as typhoeus will handle it as expected
382
+ param
383
+ else
384
+ fail "unknown collection format: #{collection_format.inspect}"
385
+ end
386
+ end
387
+
388
+ def log_response(response)
389
+ base_message = { 'message' => "Receive response from #{response.env.url}" }
390
+
391
+ if json_mime?(response.headers['Content-Type'])
392
+ @config.logger.info(base_message.merge('http_response' => response.to_hash))
393
+ else
394
+ @config.logger.info(base_message)
395
+ end
396
+ end
397
+ end
398
+ end