snap_business 1.0.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 (31) hide show
  1. checksums.yaml +7 -0
  2. data/lib/snap_business/api/conversion_api.rb +244 -0
  3. data/lib/snap_business/api/default_api.rb +266 -0
  4. data/lib/snap_business/api_client.rb +428 -0
  5. data/lib/snap_business/api_error.rb +57 -0
  6. data/lib/snap_business/configuration.rb +318 -0
  7. data/lib/snap_business/models/capi_event.rb +590 -0
  8. data/lib/snap_business/models/capi_event_ext.rb +58 -0
  9. data/lib/snap_business/models/response.rb +237 -0
  10. data/lib/snap_business/models/response_error_records.rb +228 -0
  11. data/lib/snap_business/models/response_logs.rb +237 -0
  12. data/lib/snap_business/models/response_logs_log.rb +284 -0
  13. data/lib/snap_business/models/response_stats.rb +235 -0
  14. data/lib/snap_business/models/response_stats_data.rb +226 -0
  15. data/lib/snap_business/models/response_stats_test.rb +226 -0
  16. data/lib/snap_business/models/test_response.rb +259 -0
  17. data/lib/snap_business/models/validated_fields.rb +226 -0
  18. data/lib/snap_business/models/validated_fields_items.rb +262 -0
  19. data/lib/snap_business/models/validated_fields_validated_fields.rb +262 -0
  20. data/lib/snap_business/util/capi_hash.rb +61 -0
  21. data/lib/snap_business/util/constants.rb +16 -0
  22. data/lib/snap_business/version.rb +15 -0
  23. data/lib/snap_business.rb +52 -0
  24. data/spec/api/conversion_api_spec.rb +203 -0
  25. data/spec/api/default_api_spec.rb +45 -0
  26. data/spec/api_client_spec.rb +188 -0
  27. data/spec/configuration_spec.rb +42 -0
  28. data/spec/models/capi_event_spec.rb +127 -0
  29. data/spec/spec_helper.rb +111 -0
  30. data/spec/util/capi_hash_spec.rb +62 -0
  31. metadata +178 -0
@@ -0,0 +1,428 @@
1
+ =begin
2
+ #Snap Conversions API
3
+
4
+ #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
5
+
6
+ The version of the OpenAPI document: 1.0.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 6.0.1
10
+
11
+ =end
12
+
13
+ require 'date'
14
+ require 'json'
15
+ require 'logger'
16
+ require 'tempfile'
17
+ require 'time'
18
+ require 'faraday'
19
+ require 'faraday/multipart' if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new('2.0')
20
+
21
+ module SnapBusinessSDK
22
+ class ApiClient
23
+ # The Configuration object holding settings to be used in the API client.
24
+ attr_accessor :config
25
+
26
+ # Defines the headers to be used in HTTP requests of all API calls by default.
27
+ #
28
+ # @return [Hash]
29
+ attr_accessor :default_headers
30
+
31
+ # Initializes the ApiClient
32
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
33
+ def initialize(config = Configuration.default)
34
+ @config = config
35
+ @user_agent = "OpenAPI-Generator/#{VERSION}/ruby"
36
+ @default_headers = {
37
+ 'Content-Type' => 'application/json',
38
+ 'User-Agent' => @user_agent
39
+ }
40
+ end
41
+
42
+ def self.default
43
+ @@default ||= ApiClient.new
44
+ end
45
+
46
+ # Call an API with given options.
47
+ #
48
+ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements:
49
+ # the data deserialized from response body (could be nil), response status code and response headers.
50
+ def call_api(http_method, path, opts = {})
51
+ begin
52
+ response = connection(opts).public_send(http_method.to_sym.downcase) do |req|
53
+ build_request(http_method, path, req, opts)
54
+ end
55
+
56
+ if config.debugging
57
+ config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
58
+ end
59
+
60
+ unless response.success?
61
+ if response.status == 0
62
+ # Errors from libcurl will be made visible here
63
+ fail ApiError.new(code: 0,
64
+ message: response.return_message)
65
+ else
66
+ fail ApiError.new(code: response.status,
67
+ response_headers: response.headers,
68
+ response_body: response.body),
69
+ response.reason_phrase
70
+ end
71
+ end
72
+ rescue Faraday::TimeoutError
73
+ fail ApiError.new('Connection timed out')
74
+ end
75
+
76
+ if opts[:return_type]
77
+ data = deserialize(response, opts[:return_type])
78
+ else
79
+ data = nil
80
+ end
81
+ return data, response.status, response.headers
82
+ end
83
+
84
+ # Builds the HTTP request
85
+ #
86
+ # @param [String] http_method HTTP method/verb (e.g. POST)
87
+ # @param [String] path URL path (e.g. /account/new)
88
+ # @option opts [Hash] :header_params Header parameters
89
+ # @option opts [Hash] :query_params Query parameters
90
+ # @option opts [Hash] :form_params Query parameters
91
+ # @option opts [Object] :body HTTP body (JSON/XML)
92
+ # @return [Faraday::Request] A Faraday Request
93
+ def build_request(http_method, path, request, opts = {})
94
+ url = build_request_url(path, opts)
95
+ http_method = http_method.to_sym.downcase
96
+
97
+ header_params = @default_headers.merge(opts[:header_params] || {})
98
+ query_params = opts[:query_params] || {}
99
+ form_params = opts[:form_params] || {}
100
+
101
+ update_params_for_auth! header_params, query_params, opts[:auth_names]
102
+
103
+ if [:post, :patch, :put, :delete].include?(http_method)
104
+ req_body = build_request_body(header_params, form_params, opts[:body])
105
+ if config.debugging
106
+ config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
107
+ config.logger.debug "HTTP request headers: #{header_params}"
108
+ config.logger.debug "HTTP request to url: #{url}"
109
+ end
110
+ end
111
+ request.headers = header_params
112
+ request.body = req_body
113
+
114
+ # Overload default options only if provided
115
+ request.options.params_encoder = config.params_encoder if config.params_encoder
116
+ request.options.timeout = config.timeout if config.timeout
117
+ # request.options.verbose = config.debugging if config.debugging
118
+
119
+ request.url url
120
+ request.params = query_params
121
+ download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary'
122
+ request
123
+ end
124
+
125
+ # Builds the HTTP request body
126
+ #
127
+ # @param [Hash] header_params Header parameters
128
+ # @param [Hash] form_params Query parameters
129
+ # @param [Object] body HTTP body (JSON/XML)
130
+ # @return [String] HTTP body data in the form of string
131
+ def build_request_body(header_params, form_params, body)
132
+ # http form
133
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded'
134
+ data = URI.encode_www_form(form_params)
135
+ elsif header_params['Content-Type'] == 'multipart/form-data'
136
+ data = {}
137
+ form_params.each do |key, value|
138
+ case value
139
+ when ::File, ::Tempfile
140
+ # TODO hardcode to application/octet-stream, need better way to detect content type
141
+ data[key] = Faraday::UploadIO.new(value.path, 'application/octet-stream', value.path)
142
+ when ::Array, nil
143
+ # let Faraday handle Array and nil parameters
144
+ data[key] = value
145
+ else
146
+ data[key] = value.to_s
147
+ end
148
+ end
149
+ elsif body
150
+ data = body.is_a?(String) ? body : body.to_json
151
+ else
152
+ data = nil
153
+ end
154
+ data
155
+ end
156
+
157
+ def download_file(request)
158
+ @stream = []
159
+
160
+ # handle streaming Responses
161
+ request.options.on_data = Proc.new do |chunk, overall_received_bytes|
162
+ @stream << chunk
163
+ end
164
+ end
165
+
166
+ def connection(opts)
167
+ opts[:header_params]['Content-Type'] == 'multipart/form-data' ? connection_multipart : connection_regular
168
+ end
169
+
170
+ def connection_multipart
171
+ @connection_multipart ||= build_connection do |conn|
172
+ conn.request :multipart
173
+ conn.request :url_encoded
174
+ end
175
+ end
176
+
177
+ def connection_regular
178
+ @connection_regular ||= build_connection
179
+ end
180
+
181
+ def build_connection
182
+ Faraday.new(url: config.base_url, ssl: ssl_options) do |conn|
183
+ basic_auth(conn)
184
+ config.configure_middleware(conn)
185
+ yield(conn) if block_given?
186
+ conn.adapter(Faraday.default_adapter)
187
+ end
188
+ end
189
+
190
+ def ssl_options
191
+ {
192
+ ca_file: config.ssl_ca_file,
193
+ verify: config.ssl_verify,
194
+ verify_mode: config.ssl_verify_mode,
195
+ client_cert: config.ssl_client_cert,
196
+ client_key: config.ssl_client_key
197
+ }
198
+ end
199
+
200
+ def basic_auth(conn)
201
+ if config.username && config.password
202
+ if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new('2.0')
203
+ conn.request(:authorization, :basic, config.username, config.password)
204
+ else
205
+ conn.request(:basic_auth, config.username, config.password)
206
+ end
207
+ end
208
+ end
209
+
210
+ # Check if the given MIME is a JSON MIME.
211
+ # JSON MIME examples:
212
+ # application/json
213
+ # application/json; charset=UTF8
214
+ # APPLICATION/JSON
215
+ # */*
216
+ # @param [String] mime MIME
217
+ # @return [Boolean] True if the MIME is application/json
218
+ def json_mime?(mime)
219
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
220
+ end
221
+
222
+ # Deserialize the response to the given return type.
223
+ #
224
+ # @param [Response] response HTTP response
225
+ # @param [String] return_type some examples: "User", "Array<User>", "Hash<String, Integer>"
226
+ def deserialize(response, return_type)
227
+ body = response.body
228
+
229
+ # handle file downloading - return the File instance processed in request callbacks
230
+ # note that response body is empty when the file is written in chunks in request on_body callback
231
+ if return_type == 'File'
232
+ if @config.return_binary_data == true
233
+ # return byte stream
234
+ encoding = body.encoding
235
+ return @stream.join.force_encoding(encoding)
236
+ else
237
+ # return file instead of binary data
238
+ content_disposition = response.headers['Content-Disposition']
239
+ if content_disposition && content_disposition =~ /filename=/i
240
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
241
+ prefix = sanitize_filename(filename)
242
+ else
243
+ prefix = 'download-'
244
+ end
245
+ prefix = prefix + '-' unless prefix.end_with?('-')
246
+ encoding = body.encoding
247
+ @tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
248
+ @tempfile.write(@stream.join.force_encoding(encoding))
249
+ @tempfile.close
250
+ @config.logger.info "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\
251
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
252
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
253
+ "explicitly with `tempfile.delete`"
254
+ return @tempfile
255
+ end
256
+ end
257
+
258
+ return nil if body.nil? || body.empty?
259
+
260
+ # return response body directly for String return type
261
+ return body if return_type == 'String'
262
+
263
+ # ensuring a default content type
264
+ content_type = response.headers['Content-Type'] || 'application/json'
265
+
266
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
267
+
268
+ begin
269
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
270
+ rescue JSON::ParserError => e
271
+ if %w(String Date Time).include?(return_type)
272
+ data = body
273
+ else
274
+ raise e
275
+ end
276
+ end
277
+
278
+ convert_to_type data, return_type
279
+ end
280
+
281
+ # Convert data to the given return type.
282
+ # @param [Object] data Data to be converted
283
+ # @param [String] return_type Return type
284
+ # @return [Mixed] Data in a particular type
285
+ def convert_to_type(data, return_type)
286
+ return nil if data.nil?
287
+ case return_type
288
+ when 'String'
289
+ data.to_s
290
+ when 'Integer'
291
+ data.to_i
292
+ when 'Float'
293
+ data.to_f
294
+ when 'Boolean'
295
+ data == true
296
+ when 'Time'
297
+ # parse date time (expecting ISO 8601 format)
298
+ Time.parse data
299
+ when 'Date'
300
+ # parse date time (expecting ISO 8601 format)
301
+ Date.parse data
302
+ when 'Object'
303
+ # generic object (usually a Hash), return directly
304
+ data
305
+ when /\AArray<(.+)>\z/
306
+ # e.g. Array<Pet>
307
+ sub_type = $1
308
+ data.map { |item| convert_to_type(item, sub_type) }
309
+ when /\AHash\<String, (.+)\>\z/
310
+ # e.g. Hash<String, Integer>
311
+ sub_type = $1
312
+ {}.tap do |hash|
313
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
314
+ end
315
+ else
316
+ # models (e.g. Pet) or oneOf
317
+ klass = SnapBusinessSDK.const_get(return_type)
318
+ klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data)
319
+ end
320
+ end
321
+
322
+ # Sanitize filename by removing path.
323
+ # e.g. ../../sun.gif becomes sun.gif
324
+ #
325
+ # @param [String] filename the filename to be sanitized
326
+ # @return [String] the sanitized filename
327
+ def sanitize_filename(filename)
328
+ filename.gsub(/.*[\/\\]/, '')
329
+ end
330
+
331
+ def build_request_url(path, opts = {})
332
+ # Add leading and trailing slashes to path
333
+ path = "/#{path}".gsub(/\/+/, '/')
334
+ @config.base_url(opts[:operation]) + path
335
+ end
336
+
337
+ # Update header and query params based on authentication settings.
338
+ #
339
+ # @param [Hash] header_params Header parameters
340
+ # @param [Hash] query_params Query parameters
341
+ # @param [String] auth_names Authentication scheme name
342
+ def update_params_for_auth!(header_params, query_params, auth_names)
343
+ Array(auth_names).each do |auth_name|
344
+ auth_setting = @config.auth_settings[auth_name]
345
+ next unless auth_setting
346
+ case auth_setting[:in]
347
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
348
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
349
+ else fail ArgumentError, 'Authentication token must be in `query` or `header`'
350
+ end
351
+ end
352
+ end
353
+
354
+ # Sets user agent in HTTP header
355
+ #
356
+ # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0)
357
+ def user_agent=(user_agent)
358
+ @user_agent = user_agent
359
+ @default_headers['User-Agent'] = @user_agent
360
+ end
361
+
362
+ # Return Accept header based on an array of accepts provided.
363
+ # @param [Array] accepts array for Accept
364
+ # @return [String] the Accept header (e.g. application/json)
365
+ def select_header_accept(accepts)
366
+ return nil if accepts.nil? || accepts.empty?
367
+ # use JSON when present, otherwise use all of the provided
368
+ json_accept = accepts.find { |s| json_mime?(s) }
369
+ json_accept || accepts.join(',')
370
+ end
371
+
372
+ # Return Content-Type header based on an array of content types provided.
373
+ # @param [Array] content_types array for Content-Type
374
+ # @return [String] the Content-Type header (e.g. application/json)
375
+ def select_header_content_type(content_types)
376
+ # return nil by default
377
+ return if content_types.nil? || content_types.empty?
378
+ # use JSON when present, otherwise use the first one
379
+ json_content_type = content_types.find { |s| json_mime?(s) }
380
+ json_content_type || content_types.first
381
+ end
382
+
383
+ # Convert object (array, hash, object, etc) to JSON string.
384
+ # @param [Object] model object to be converted into JSON string
385
+ # @return [String] JSON string representation of the object
386
+ def object_to_http_body(model)
387
+ return model if model.nil? || model.is_a?(String)
388
+ local_body = nil
389
+ if model.is_a?(Array)
390
+ local_body = model.map { |m| object_to_hash(m) }
391
+ else
392
+ local_body = object_to_hash(model)
393
+ end
394
+ local_body.to_json
395
+ end
396
+
397
+ # Convert object(non-array) to hash.
398
+ # @param [Object] obj object to be converted into JSON string
399
+ # @return [String] JSON string representation of the object
400
+ def object_to_hash(obj)
401
+ if obj.respond_to?(:to_hash)
402
+ obj.to_hash
403
+ else
404
+ obj
405
+ end
406
+ end
407
+
408
+ # Build parameter value according to the given collection format.
409
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
410
+ def build_collection_param(param, collection_format)
411
+ case collection_format
412
+ when :csv
413
+ param.join(',')
414
+ when :ssv
415
+ param.join(' ')
416
+ when :tsv
417
+ param.join("\t")
418
+ when :pipes
419
+ param.join('|')
420
+ when :multi
421
+ # return the array directly as typhoeus will handle it as expected
422
+ param
423
+ else
424
+ fail "unknown collection format: #{collection_format.inspect}"
425
+ end
426
+ end
427
+ end
428
+ end
@@ -0,0 +1,57 @@
1
+ =begin
2
+ #Snap Conversions API
3
+
4
+ #No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
5
+
6
+ The version of the OpenAPI document: 1.0.0
7
+
8
+ Generated by: https://openapi-generator.tech
9
+ OpenAPI Generator version: 6.0.1
10
+
11
+ =end
12
+
13
+ module SnapBusinessSDK
14
+ class ApiError < StandardError
15
+ attr_reader :code, :response_headers, :response_body
16
+
17
+ # Usage examples:
18
+ # ApiError.new
19
+ # ApiError.new("message")
20
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
21
+ # ApiError.new(:code => 404, :message => "Not Found")
22
+ def initialize(arg = nil)
23
+ if arg.is_a? Hash
24
+ if arg.key?(:message) || arg.key?('message')
25
+ super(arg[:message] || arg['message'])
26
+ else
27
+ super arg
28
+ end
29
+
30
+ arg.each do |k, v|
31
+ instance_variable_set "@#{k}", v
32
+ end
33
+ else
34
+ super arg
35
+ end
36
+ end
37
+
38
+ # Override to_s to display a friendly error message
39
+ def to_s
40
+ message
41
+ end
42
+
43
+ def message
44
+ if @message.nil?
45
+ msg = "Error message: the server returns an error"
46
+ else
47
+ msg = @message
48
+ end
49
+
50
+ msg += "\nHTTP status code: #{code}" if code
51
+ msg += "\nResponse headers: #{response_headers}" if response_headers
52
+ msg += "\nResponse body: #{response_body}" if response_body
53
+
54
+ msg
55
+ end
56
+ end
57
+ end