minato_ruby_api_client 0.2.1

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 +7 -0
  2. data/CHANGELOG.md +23 -0
  3. data/Dockerfile +1 -0
  4. data/Gemfile +17 -0
  5. data/Gemfile.lock +398 -0
  6. data/README.md +54 -0
  7. data/Rakefile +10 -0
  8. data/compose.yml +11 -0
  9. data/coverage/.last_run.json +5 -0
  10. data/coverage/.resultset.json +1248 -0
  11. data/coverage/.resultset.json.lock +0 -0
  12. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_asc.png +0 -0
  13. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_asc_disabled.png +0 -0
  14. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_both.png +0 -0
  15. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_desc.png +0 -0
  16. data/coverage/assets/0.12.3/DataTables-1.10.20/images/sort_desc_disabled.png +0 -0
  17. data/coverage/assets/0.12.3/application.css +1 -0
  18. data/coverage/assets/0.12.3/application.js +7 -0
  19. data/coverage/assets/0.12.3/colorbox/border.png +0 -0
  20. data/coverage/assets/0.12.3/colorbox/controls.png +0 -0
  21. data/coverage/assets/0.12.3/colorbox/loading.gif +0 -0
  22. data/coverage/assets/0.12.3/colorbox/loading_background.png +0 -0
  23. data/coverage/assets/0.12.3/favicon_green.png +0 -0
  24. data/coverage/assets/0.12.3/favicon_red.png +0 -0
  25. data/coverage/assets/0.12.3/favicon_yellow.png +0 -0
  26. data/coverage/assets/0.12.3/images/ui-bg_flat_0_aaaaaa_40x100.png +0 -0
  27. data/coverage/assets/0.12.3/images/ui-bg_flat_75_ffffff_40x100.png +0 -0
  28. data/coverage/assets/0.12.3/images/ui-bg_glass_55_fbf9ee_1x400.png +0 -0
  29. data/coverage/assets/0.12.3/images/ui-bg_glass_65_ffffff_1x400.png +0 -0
  30. data/coverage/assets/0.12.3/images/ui-bg_glass_75_dadada_1x400.png +0 -0
  31. data/coverage/assets/0.12.3/images/ui-bg_glass_75_e6e6e6_1x400.png +0 -0
  32. data/coverage/assets/0.12.3/images/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  33. data/coverage/assets/0.12.3/images/ui-bg_highlight-soft_75_cccccc_1x100.png +0 -0
  34. data/coverage/assets/0.12.3/images/ui-icons_222222_256x240.png +0 -0
  35. data/coverage/assets/0.12.3/images/ui-icons_2e83ff_256x240.png +0 -0
  36. data/coverage/assets/0.12.3/images/ui-icons_454545_256x240.png +0 -0
  37. data/coverage/assets/0.12.3/images/ui-icons_888888_256x240.png +0 -0
  38. data/coverage/assets/0.12.3/images/ui-icons_cd0a0a_256x240.png +0 -0
  39. data/coverage/assets/0.12.3/loading.gif +0 -0
  40. data/coverage/assets/0.12.3/magnify.png +0 -0
  41. data/coverage/index.html +13728 -0
  42. data/lib/minato_ruby_api_client/api_client.rb +389 -0
  43. data/lib/minato_ruby_api_client/api_error.rb +16 -0
  44. data/lib/minato_ruby_api_client/configuration.rb +247 -0
  45. data/lib/minato_ruby_api_client/version.rb +3 -0
  46. data/lib/minato_ruby_api_client.rb +24 -0
  47. data/minato_ruby_api_client.gemspec +35 -0
  48. data/spec/api_client_spec.rb +309 -0
  49. data/spec/configuration_spec.rb +204 -0
  50. data/spec/minato_ruby_api_client_spec.rb +17 -0
  51. data/spec/spec_helper.rb +105 -0
  52. metadata +165 -0
@@ -0,0 +1,389 @@
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
@@ -0,0 +1,16 @@
1
+ require 'minato_error_handler'
2
+
3
+ module MinatoRubyApiClient
4
+ class ApiError < MinatoErrorHandler::Errors::ExternalError
5
+ attr_reader :status_code
6
+
7
+ def initialize(res: nil, req: nil, status_code: 500)
8
+ super(req: req, res: res)
9
+ @status_code = status_code
10
+ end
11
+
12
+ def message
13
+ "An error occurred while communicating with the API."
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,247 @@
1
+ module MinatoRubyApiClient
2
+ class Configuration
3
+ # Defines url scheme
4
+ attr_accessor :scheme
5
+
6
+ # Defines url host
7
+ attr_accessor :host
8
+
9
+ # Defines url base path
10
+ attr_accessor :base_path
11
+
12
+ # Defines user agent
13
+ attr_accessor :user_agent
14
+
15
+ # Defines API keys used with API Key authentications.
16
+ #
17
+ # @return [Hash] key: parameter name, value: parameter value (API key)
18
+ #
19
+ # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string)
20
+ # config.api_key['api_key'] = 'xxx'
21
+ attr_accessor :api_key
22
+
23
+ # Defines API key prefixes used with API Key authentications.
24
+ #
25
+ # @return [Hash] key: parameter name, value: API key prefix
26
+ #
27
+ # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers)
28
+ # config.api_key_prefix['api_key'] = 'Token'
29
+ attr_accessor :api_key_prefix
30
+
31
+ # Defines the username used with HTTP basic authentication.
32
+ #
33
+ # @return [String]
34
+ attr_accessor :username
35
+
36
+ # Defines the password used with HTTP basic authentication.
37
+ #
38
+ # @return [String]
39
+ attr_accessor :password
40
+
41
+ # Defines the access token (Bearer) used with OAuth2.
42
+ attr_accessor :access_token
43
+
44
+ # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response
45
+ # details will be logged with `logger.debug` (see the `logger` attribute).
46
+ # Default to false.
47
+ #
48
+ # @return [true, false]
49
+ attr_accessor :debugging
50
+
51
+ # Defines the logger used for debugging.
52
+ # Default to `Rails.logger` (when in Rails) or logging to STDOUT.
53
+ #
54
+ # @return [#debug]
55
+ attr_accessor :logger
56
+
57
+ # Defines the temporary folder to store downloaded files
58
+ # (for API endpoints that have file response).
59
+ # Default to use `Tempfile`.
60
+ #
61
+ # @return [String]
62
+ attr_accessor :temp_folder_path
63
+
64
+ # The time limit for HTTP request in seconds.
65
+ # Default to 0 (never times out).
66
+ attr_accessor :timeout
67
+
68
+ # Set this to false to skip client side validation in the operation.
69
+ # Default to true.
70
+ # @return [true, false]
71
+ attr_accessor :client_side_validation
72
+
73
+ ### TLS/SSL setting
74
+ # Set this to false to skip verifying SSL certificate when calling API from https server.
75
+ # Default to true.
76
+ #
77
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
78
+ #
79
+ # @return [true, false]
80
+ attr_accessor :ssl_verify
81
+
82
+ ### TLS/SSL setting
83
+ # Any `OpenSSL::SSL::` constant (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL.html)
84
+ #
85
+ # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks.
86
+ #
87
+ attr_accessor :ssl_verify_mode
88
+
89
+ ### TLS/SSL setting
90
+ # Set this to customize the certificate file to verify the peer.
91
+ #
92
+ # @return [String] the path to the certificate file
93
+ attr_accessor :ssl_ca_file
94
+
95
+ ### TLS/SSL setting
96
+ # Client certificate file (for client certificate)
97
+ attr_accessor :ssl_client_cert
98
+
99
+ ### TLS/SSL setting
100
+ # Client private key file (for client certificate)
101
+ attr_accessor :ssl_client_key
102
+
103
+ # Set this to customize parameters encoding of array parameter with multi collectionFormat.
104
+ # Default to nil.
105
+ #
106
+ # @see The params_encoding option of Ethon. Related source code:
107
+ # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96
108
+ attr_accessor :params_encoding
109
+
110
+ def initialize
111
+ @scheme = 'https'
112
+ @host = ''
113
+ @base_path = ''
114
+ @user_agent = ''
115
+ @subscription_key = ''
116
+ @api_key = {}
117
+ @api_key_prefix = {}
118
+ @client_side_validation = true
119
+ @ssl_verify = true
120
+ @ssl_verify_mode = nil
121
+ @ssl_ca_file = nil
122
+ @ssl_client_cert = nil
123
+ @ssl_client_key = nil
124
+ @middlewares = []
125
+ @request_middlewares = []
126
+ @response_middlewares = []
127
+ @timeout = 60
128
+ @debugging = false
129
+ @logger = Object.const_defined?(:Rails) ? Rails.logger : Logger.new(STDOUT)
130
+
131
+ yield(self) if block_given?
132
+ end
133
+
134
+ # The default Configuration object.
135
+ def self.default
136
+ @@default ||= Configuration.new
137
+ end
138
+
139
+ def configure
140
+ yield(self) if block_given?
141
+ end
142
+
143
+ def scheme=(scheme)
144
+ # remove :// from scheme
145
+ @scheme = scheme.sub(/:\/\//, '')
146
+ end
147
+
148
+ def host=(host)
149
+ # remove http(s):// and anything after a slash
150
+ @host = host.sub(/https?:\/\//, '').split('/').first
151
+ end
152
+
153
+ def base_path=(base_path)
154
+ # Add leading and trailing slashes to base_path
155
+ @base_path = "/#{base_path}".gsub(/\/+/, '/')
156
+ @base_path = '' if @base_path == '/'
157
+ end
158
+
159
+ # Returns base URL
160
+ def base_url
161
+ "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '')
162
+ end
163
+
164
+ def debugging
165
+ return @debugging if @debugging == true
166
+ ENV['MINATO_RUBY_API_CLIENT_DEBUG'] == 'true'
167
+ end
168
+
169
+ # Gets API key (with prefix if set).
170
+ # @param [String] param_name the parameter name of API key auth
171
+ def api_key_with_prefix(param_name, param_alias = nil)
172
+ key = @api_key[param_name]
173
+ key = @api_key.fetch(param_alias, key) unless param_alias.nil?
174
+ if @api_key_prefix[param_name]
175
+ "#{@api_key_prefix[param_name]} #{key}"
176
+ else
177
+ key
178
+ end
179
+ end
180
+
181
+ # Gets Basic Auth token string
182
+ def basic_auth_token
183
+ 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
184
+ end
185
+
186
+ # Returns Auth Settings hash for api client.
187
+ def auth_settings
188
+ auth_settings = {
189
+ 'bearer_auth' =>
190
+ {
191
+ type: 'bearer',
192
+ in: 'header',
193
+ key: 'Authorization',
194
+ value: "Bearer #{access_token}"
195
+ },
196
+ 'basic_auth' =>
197
+ {
198
+ type: 'basic',
199
+ in: 'header',
200
+ key: 'Authorization',
201
+ value: basic_auth_token
202
+ },
203
+ }
204
+
205
+ api_key.each do |k, v|
206
+ auth_settings['apikey'] = {
207
+ type: 'apikey',
208
+ in: 'header',
209
+ key: k,
210
+ value: api_key_with_prefix(k)
211
+ }
212
+ end
213
+
214
+ auth_settings
215
+ end
216
+
217
+ # Adds middleware to the stack
218
+ def use(*middleware)
219
+ @middlewares << middleware
220
+ end
221
+
222
+ # Adds request middleware to the stack
223
+ def request(*middleware)
224
+ @request_middlewares << middleware
225
+ end
226
+
227
+ # Adds response middleware to the stack
228
+ def response(*middleware)
229
+ @response_middlewares << middleware
230
+ end
231
+
232
+ # Set up middleware on the connection
233
+ def configure_middleware(connection)
234
+ @middlewares.each do |middleware|
235
+ connection.use(*middleware)
236
+ end
237
+
238
+ @request_middlewares.each do |middleware|
239
+ connection.request(*middleware)
240
+ end
241
+
242
+ @response_middlewares.each do |middleware|
243
+ connection.response(*middleware)
244
+ end
245
+ end
246
+ end
247
+ end
@@ -0,0 +1,3 @@
1
+ module MinatoRubyApiClient
2
+ VERSION = '0.2.1'
3
+ end
@@ -0,0 +1,24 @@
1
+ # Common files
2
+ require 'minato_ruby_api_client/api_client'
3
+ require 'minato_ruby_api_client/api_error'
4
+ require 'minato_ruby_api_client/version'
5
+ require 'minato_ruby_api_client/configuration'
6
+
7
+
8
+ module MinatoRubyApiClient
9
+ class << self
10
+ # Customize default settings for the SDK using block.
11
+ # MinatoRubyApiClient.configure do |config|
12
+ # config.username = "xxx"
13
+ # config.password = "xxx"
14
+ # end
15
+ # If no block given, return the default Configuration object.
16
+ def configure
17
+ if block_given?
18
+ yield(Configuration.default)
19
+ else
20
+ Configuration.default
21
+ end
22
+ end
23
+ end
24
+ end