tradenity 0.1.1 → 1.0.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (95) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +7 -0
  3. data/README.md +89 -77
  4. data/lib/tradenity/api_client.rb +408 -0
  5. data/lib/tradenity/api_error.rb +36 -0
  6. data/lib/tradenity/configuration.rb +205 -0
  7. data/lib/tradenity/exceptions.rb +5 -0
  8. data/lib/tradenity/rails/railtie.rb +20 -20
  9. data/lib/tradenity/resources/address.rb +729 -0
  10. data/lib/tradenity/resources/braintree_gateway.rb +804 -0
  11. data/lib/tradenity/resources/brand.rb +732 -0
  12. data/lib/tradenity/resources/cancel_operation.rb +675 -0
  13. data/lib/tradenity/resources/cart_settings.rb +219 -0
  14. data/lib/tradenity/resources/cash_on_delivery_payment.rb +746 -0
  15. data/lib/tradenity/resources/category.rb +763 -0
  16. data/lib/tradenity/resources/collection.rb +734 -0
  17. data/lib/tradenity/resources/contact_info.rb +306 -0
  18. data/lib/tradenity/resources/countries_geo_zone.rb +739 -0
  19. data/lib/tradenity/resources/country.rb +803 -0
  20. data/lib/tradenity/resources/coupon.rb +454 -0
  21. data/lib/tradenity/resources/credit_card_payment.rb +803 -0
  22. data/lib/tradenity/resources/currency.rb +762 -0
  23. data/lib/tradenity/resources/customer.rb +816 -0
  24. data/lib/tradenity/resources/customer_group.rb +723 -0
  25. data/lib/tradenity/resources/dimensions.rb +263 -0
  26. data/lib/tradenity/resources/discount_coupon.rb +811 -0
  27. data/lib/tradenity/resources/discount_promotion.rb +784 -0
  28. data/lib/tradenity/resources/fixed_rate_shipping.rb +837 -0
  29. data/lib/tradenity/resources/free_item_coupon.rb +793 -0
  30. data/lib/tradenity/resources/free_shipping.rb +806 -0
  31. data/lib/tradenity/resources/free_shipping_coupon.rb +788 -0
  32. data/lib/tradenity/resources/free_shipping_promotion.rb +744 -0
  33. data/lib/tradenity/resources/gateway.rb +435 -0
  34. data/lib/tradenity/resources/general_settings.rb +206 -0
  35. data/lib/tradenity/resources/geo_zone.rb +406 -0
  36. data/lib/tradenity/resources/instance_meta.rb +182 -0
  37. data/lib/tradenity/resources/inventory_settings.rb +197 -0
  38. data/lib/tradenity/resources/items_selector.rb +270 -0
  39. data/lib/tradenity/resources/line_item.rb +347 -0
  40. data/lib/tradenity/resources/mail_server_settings.rb +221 -0
  41. data/lib/tradenity/resources/measurement_settings.rb +253 -0
  42. data/lib/tradenity/resources/option.rb +787 -0
  43. data/lib/tradenity/resources/option_set.rb +734 -0
  44. data/lib/tradenity/resources/option_value.rb +680 -0
  45. data/lib/tradenity/resources/order.rb +929 -0
  46. data/lib/tradenity/resources/order_line_item.rb +777 -0
  47. data/lib/tradenity/resources/paging.rb +38 -0
  48. data/lib/tradenity/resources/payment.rb +429 -0
  49. data/lib/tradenity/resources/payment_card.rb +847 -0
  50. data/lib/tradenity/resources/payment_settings.rb +201 -0
  51. data/lib/tradenity/resources/payment_source.rb +392 -0
  52. data/lib/tradenity/resources/payment_token.rb +723 -0
  53. data/lib/tradenity/resources/payment_transaction.rb +740 -0
  54. data/lib/tradenity/resources/photo.rb +341 -0
  55. data/lib/tradenity/resources/product.rb +1156 -0
  56. data/lib/tradenity/resources/promotion.rb +427 -0
  57. data/lib/tradenity/resources/refund_operation.rb +358 -0
  58. data/lib/tradenity/resources/refund_transaction.rb +730 -0
  59. data/lib/tradenity/resources/return_line_item.rb +781 -0
  60. data/lib/tradenity/resources/return_operation.rb +686 -0
  61. data/lib/tradenity/resources/return_settings.rb +255 -0
  62. data/lib/tradenity/resources/shipping_method.rb +530 -0
  63. data/lib/tradenity/resources/shopping_cart.rb +647 -0
  64. data/lib/tradenity/resources/state.rb +675 -0
  65. data/lib/tradenity/resources/states_geo_zone.rb +748 -0
  66. data/lib/tradenity/resources/store_credit.rb +686 -0
  67. data/lib/tradenity/resources/store_credit_payment.rb +764 -0
  68. data/lib/tradenity/resources/store_credit_transaction.rb +730 -0
  69. data/lib/tradenity/resources/store_profile.rb +532 -0
  70. data/lib/tradenity/resources/stripe_gateway.rb +804 -0
  71. data/lib/tradenity/resources/table_rate_rule.rb +712 -0
  72. data/lib/tradenity/resources/table_rate_shipping.rb +834 -0
  73. data/lib/tradenity/resources/tax_class.rb +723 -0
  74. data/lib/tradenity/resources/tax_rate.rb +845 -0
  75. data/lib/tradenity/resources/tax_settings.rb +231 -0
  76. data/lib/tradenity/resources/test_gateway.rb +804 -0
  77. data/lib/tradenity/resources/transaction.rb +523 -0
  78. data/lib/tradenity/resources/utils.rb +7 -0
  79. data/lib/tradenity/resources/variant.rb +877 -0
  80. data/lib/tradenity/resources/web_hooks.rb +262 -0
  81. data/lib/tradenity/resources/weight.rb +235 -0
  82. data/lib/tradenity/resources/wish_list.rb +686 -0
  83. data/lib/tradenity/resources/zip_codes_geo_zone.rb +755 -0
  84. data/lib/tradenity/token_holder.rb +22 -0
  85. data/lib/tradenity/version.rb +13 -3
  86. data/lib/tradenity.rb +117 -7
  87. data/tradenity.gemspec +35 -30
  88. metadata +200 -34
  89. data/lib/tradenity/api.rb +0 -17
  90. data/lib/tradenity/error/exceptions.rb +0 -52
  91. data/lib/tradenity/error/message.rb +0 -38
  92. data/lib/tradenity/http/client.rb +0 -130
  93. data/lib/tradenity/model/base.rb +0 -100
  94. data/lib/tradenity/model/entities.rb +0 -390
  95. data/lib/tradenity/model/paging.rb +0 -23
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: 7b7ab13c558e7a4a92341acd33f05dcc81ce5b03
4
- data.tar.gz: 8f320b23904cacc7084d404a5086b2fad3111d40
2
+ SHA256:
3
+ metadata.gz: f31074c0e2dd82afba82214f8563565c69e740112be8a9e26044ff3c807a02d6
4
+ data.tar.gz: 5a8d571c969e11bc37644cd8de1b8fe9adbc83912b66694b9f4c79bef6c383cd
5
5
  SHA512:
6
- metadata.gz: 4880c390ce6092b2a7b735dd70c35cc05894ccda7f91663178efaf1788b4f58a78051215c0c855b904e9ca06a2f450efa78826f3d361761f517215e57d5d6a5f
7
- data.tar.gz: 2a2c4fb63a1f3cca599ed9eae7fe2b430f039a261a409670793cda8ac829be86e37e8f459578546fdffa5051d5ac4e0403ce57315b1f91a7d913fb47356d4dc1
6
+ metadata.gz: 5eefc659b20afd8fe77cfe601695da2c24d007b7e8870604b9ca7699eeccda770157efc13616a995756aab3496834d636e57f431c04536aafa763d9fc3a05452
7
+ data.tar.gz: dd019d79b09b3236ad750efe54b28ec72b1607eca93b21fc3fa7b1cf2eb61ca9978111f1cd9f007f2e54a28b942f4f8dd6fce5e59362e82de09c929d6ac71125
data/CHANGELOG.md CHANGED
@@ -1,6 +1,13 @@
1
1
  Changelog
2
2
  ======
3
3
 
4
+
5
+ ## Version 1.0.0
6
+
7
+ - Improvement: Completely new SDK for the final v1 Tradenity REST API protocol
8
+ - Feature: Various new classes for new Tradenity resources.
9
+
10
+
4
11
  ## Version 0.1.1
5
12
 
6
13
  - Feature: Add SessionExpiredException
data/README.md CHANGED
@@ -1,77 +1,89 @@
1
- Welcome to Ruby SDK for Tradenity ecommerce REST API
2
- ====================================================
3
-
4
-
5
- ## Prerequisites
6
-
7
- To use the Tradenity SDK, you must have:
8
-
9
- - Working Ruby development environment (currently v1.9.3 and v2.2.x are supported).
10
- - Active account in [Tradenity](http://www.tradenity.com)
11
-
12
-
13
- ## Installation
14
-
15
- You can install the Ruby SDK using the standard `gem` tool.
16
-
17
- `gem install tradenity`
18
-
19
-
20
- ## Setup your credentials
21
-
22
- First of all, you have to get API keys for your store, you can find it in your store `Edit` page.
23
- To get there navigate to the stores list page, click on the `Edit` button next to your store name, scroll down till you find the `API Keys` section.
24
-
25
-
26
- ## Initialize the library
27
-
28
- With the API key in hand, you can initialize the Tradenity client.
29
- Tradenity client needs the API key and an instance of AuthTokenHolder
30
- which is an object that makes Tradenity session integrates with the web framework's session mechanism.
31
- The SDK provide implementation for Flask and Django. It's easy to implement your own for other frameworks, It is a simple 3 method interface.
32
-
33
-
34
-
35
- ```ruby
36
-
37
- require 'Tradenity'
38
-
39
- Tradenity.api_key = 'sk_xxxxxxxxxxxxx'
40
-
41
- ```
42
- Make sure to replace the api keys with the ones for your store, otherwise you will get authentication error
43
-
44
- ## Make your First call
45
-
46
- The Tradenity SDK is organized into a group of model entitiy classes that corresponds to the REST API's resources, each encapsulate the operation for a specific entity model,
47
- for example to perform operations related to the `Brand` resource you can use the corresponding `tradenity.sdk.entities.Brand` class.
48
-
49
-
50
-
51
- Now, just call any method in your code.
52
-
53
- ```ruby
54
-
55
- @brand = Brand.find_by_id("1243-9786786-jhgjtu-789s6i")
56
-
57
- ```
58
-
59
-
60
- ## Tutorials and sample applications
61
-
62
- We provide 2 sample applications, actually it is the same application implemented using 2 frameworks: `Rails`, and `Sinatra`.
63
-
64
- [Camera store sample application live demo](http://camera-store-sample.tradenity.com/)
65
-
66
- You can find the code at github:
67
-
68
- [Camera store for rails code](https://github.com/tradenity/camerastore-ruby-rails-sample).
69
-
70
- [Camera store for sinatra code](https://github.com/tradenity/camerastore-ruby-sinatra-sample).
71
-
72
- We also provide a detailed explanation of the code of these sample applications in the form of a step by step tutorials:
73
-
74
- [Camera store for rails tutorial](/kb/tutorials/ruby/rails).
75
-
76
- [Camera store for sinatra tutorial](/kb/tutorials/ruby/sinatra).
77
-
1
+ Welcome to Ruby SDK for Tradenity ecommerce API
2
+ ====================================================
3
+
4
+ This is the official Ruby SDK for [Tradenity ecommerce API](https://www.tradenity.com).
5
+
6
+ ## Prerequisites
7
+
8
+ To use the Tradenity SDK, you must have:
9
+
10
+ - Working Ruby development environment (currently v1.9.3 and v2.4.x are supported).
11
+ - Active account in [Tradenity](http://www.tradenity.com)
12
+
13
+
14
+ ## Installation
15
+
16
+ You can install the Ruby SDK using the standard `gem` tool.
17
+
18
+ `gem install tradenity`
19
+
20
+
21
+ ## Create store and load sample data
22
+
23
+ - If you are not yet registered, create a new [Tradenity account](https://www.tradenity.com).
24
+ - After you login to your account, go to [Getting started](https://admin.tradenity.com/admin/getting_started) page and create new store. you may click "Create sample store" to create a new store and populate it with sample data
25
+ - From the administration side menu, choose "Developers" > "API Keys", you can use the default key or generate a new one.
26
+
27
+
28
+ ## Setup your credentials
29
+
30
+ First of all, you have to get API keys for your store, you can find it in your store `Edit` page.
31
+ To get there navigate to the stores list page, click on the `Edit` button next to your store name, scroll down till you find the `API Keys` section.
32
+
33
+
34
+ ## Initialize the library
35
+
36
+ With the API key in hand, you can initialize the Tradenity client.
37
+ Tradenity client needs the API key and an instance of AuthTokenHolder
38
+ which is an object that makes Tradenity session integrates with the web framework's session mechanism.
39
+ The SDK provide implementation for Flask and Django. It's easy to implement your own for other frameworks, It is a simple 3 method interface.
40
+
41
+
42
+
43
+ ```ruby
44
+
45
+ require 'Tradenity'
46
+
47
+ Tradenity.configure do |config|
48
+ config.username = "sk_xxxxxxxxxxxxxxxxxxxxxxxxx"
49
+ config.password = ""
50
+ config.session_token_holder = Tradenity::SessionTokenHolder.new
51
+ end
52
+
53
+ ```
54
+ Make sure to replace the api keys with the ones for your store, otherwise you will get authentication error
55
+
56
+ ## Make your First call
57
+
58
+ The Tradenity SDK is organized into a group of model entitiy classes that corresponds to the REST API's resources, each encapsulate the operation for a specific entity model,
59
+ for example to perform operations related to the `Brand` resource you can use the corresponding `tradenity.resources.Brand` class.
60
+
61
+
62
+
63
+ Now, just call any method in your code.
64
+
65
+ ```ruby
66
+
67
+ @brand = Brand.find_by_id("1243-9786786-jhgjtu-789s6i")
68
+
69
+ ```
70
+
71
+
72
+ ## Tutorials and sample applications
73
+
74
+ We provide 2 sample applications, actually it is the same application implemented using 2 frameworks: `Rails`, and `Sinatra`.
75
+
76
+ [Camera store sample application live demo](http://camera-store-sample.tradenity.com/)
77
+
78
+ You can find the code at github:
79
+
80
+ [Camera store for rails code](https://github.com/tradenity/camerastore-ruby-rails-sample).
81
+
82
+ [Camera store for sinatra code](https://github.com/tradenity/camerastore-ruby-sinatra-sample).
83
+
84
+ We also provide a detailed explanation of the code of these sample applications in the form of a step by step tutorials:
85
+
86
+ [Camera store for rails tutorial](/kb/tutorials/ruby/rails).
87
+
88
+ [Camera store for sinatra tutorial](/kb/tutorials/ruby/sinatra).
89
+
@@ -0,0 +1,408 @@
1
+ =begin
2
+ #Tradenity API
3
+
4
+ #Tradenity eCommerce Rest API
5
+
6
+ Contact: support@tradenity.com
7
+ Generated by: https://github.com/tradenity
8
+
9
+ =end
10
+
11
+ require 'date'
12
+ require 'json'
13
+ require 'logger'
14
+ require 'tempfile'
15
+ require 'typhoeus'
16
+ require 'uri'
17
+
18
+ module Tradenity
19
+
20
+ class ApiClient
21
+
22
+ AUTH_TOKEN_HEADER_NAME = 'X-Tradenity-Session-ID'
23
+
24
+ # The Configuration object holding settings to be used in the API client.
25
+ attr_accessor :config
26
+
27
+ # Defines the headers to be used in HTTP requests of all API calls by default.
28
+ #
29
+ # @return [Hash]
30
+ attr_accessor :default_headers
31
+
32
+ attr_accessor :session_token_holder
33
+
34
+ # Initializes the ApiClient
35
+ # @option config [Configuration] Configuration for initializing the object, default to Configuration.default
36
+ def initialize(config = Configuration.default)
37
+ @config = config
38
+ @user_agent = "TradenityClient/1.0.0/Ruby"
39
+ @session_token_holder = @config.session_token_holder
40
+ @default_headers = {
41
+ 'Content-Type' => 'application/json',
42
+ 'User-Agent' => @user_agent
43
+ }
44
+ end
45
+
46
+ def self.default
47
+ @@default ||= ApiClient.new
48
+ end
49
+
50
+ # Call an API with given options.
51
+ #
52
+ # @return [Array<(Object, Fixnum, Hash)>] an array of 3 elements:
53
+ # the data deserialized from response body (could be nil), response status code and response headers.
54
+ def call_api(http_method, path, opts = {})
55
+ request = build_request(http_method, path, opts)
56
+ response = request.run
57
+
58
+ if @config.debugging
59
+ @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n"
60
+ end
61
+
62
+ unless response.success?
63
+ if response.timed_out?
64
+ fail ApiError.new('Connection timed out')
65
+ elsif response.code == 0
66
+ # Errors from libcurl will be made visible here
67
+ fail ApiError.new(:code => 0,
68
+ :message => response.return_message)
69
+ else
70
+ fail ApiError.new(:code => response.code,
71
+ :response_headers => response.headers,
72
+ :response_body => response.body),
73
+ response.status_message
74
+ end
75
+ end
76
+
77
+ if response.headers[AUTH_TOKEN_HEADER_NAME]
78
+ @session_token_holder.set_token(response.headers[AUTH_TOKEN_HEADER_NAME])
79
+ end
80
+
81
+ if opts[:return_type]
82
+ data = deserialize(response, opts[:return_type])
83
+ else
84
+ data = nil
85
+ end
86
+ return data, response.code, response.headers
87
+ end
88
+
89
+ # Builds the HTTP request
90
+ #
91
+ # @param [String] http_method HTTP method/verb (e.g. POST)
92
+ # @param [String] path URL path (e.g. /account/new)
93
+ # @option opts [Hash] :header_params Header parameters
94
+ # @option opts [Hash] :query_params Query parameters
95
+ # @option opts [Hash] :form_params Query parameters
96
+ # @option opts [Object] :body HTTP body (JSON/XML)
97
+ # @return [Typhoeus::Request] A Typhoeus Request
98
+ def build_request(http_method, path, opts = {})
99
+ url = build_request_url(path)
100
+ http_method = http_method.to_sym.downcase
101
+
102
+ header_params = @default_headers.merge(opts[:header_params] || {})
103
+ if @session_token_holder.has_token?
104
+ header_params[AUTH_TOKEN_HEADER_NAME] = @session_token_holder.get_token
105
+ else
106
+ header_params[:Authorization] = @config.basic_auth_token
107
+ end
108
+ query_params = opts[:query_params] || {}
109
+ form_params = opts[:form_params] || {}
110
+
111
+
112
+ # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false)
113
+ _verify_ssl_host = @config.verify_ssl_host ? 2 : 0
114
+
115
+ req_opts = {
116
+ :method => http_method,
117
+ :headers => header_params,
118
+ :params => query_params,
119
+ :params_encoding => @config.params_encoding,
120
+ :timeout => @config.timeout,
121
+ :ssl_verifypeer => @config.verify_ssl,
122
+ :ssl_verifyhost => _verify_ssl_host,
123
+ :sslcert => @config.cert_file,
124
+ :sslkey => @config.key_file,
125
+ :verbose => @config.debugging
126
+ }
127
+
128
+ # set custom cert, if provided
129
+ req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert
130
+
131
+ if [:post, :patch, :put, :delete].include?(http_method)
132
+ req_body = build_request_body(header_params, form_params, opts[:body])
133
+ req_opts.update :body => req_body
134
+ if @config.debugging
135
+ @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n"
136
+ end
137
+ end
138
+
139
+ request = Typhoeus::Request.new(url, req_opts)
140
+ download_file(request) if opts[:return_type] == 'File'
141
+ request
142
+ end
143
+
144
+ # Check if the given MIME is a JSON MIME.
145
+ # JSON MIME examples:
146
+ # application/json
147
+ # application/json; charset=UTF8
148
+ # APPLICATION/JSON
149
+ # */*
150
+ # @param [String] mime MIME
151
+ # @return [Boolean] True if the MIME is application/json
152
+ def json_mime?(mime)
153
+ (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil?
154
+ end
155
+
156
+ # Deserialize the response to the given return type.
157
+ #
158
+ # @param [Response] response HTTP response
159
+ # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
160
+ def deserialize(response, return_type)
161
+ body = response.body
162
+
163
+ # handle file downloading - return the File instance processed in request callbacks
164
+ # note that response body is empty when the file is written in chunks in request on_body callback
165
+ return @tempfile if return_type == 'File'
166
+
167
+ return nil if body.nil? || body.empty?
168
+
169
+ # return response body directly for String return type
170
+ return body if return_type == 'String'
171
+
172
+ # ensuring a default content type
173
+ content_type = response.headers['Content-Type'] || 'application/json'
174
+
175
+ fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type)
176
+
177
+ begin
178
+ data = JSON.parse("[#{body}]", :symbolize_names => true)[0]
179
+ rescue JSON::ParserError => e
180
+ if %w(String Date DateTime).include?(return_type)
181
+ data = body
182
+ else
183
+ raise e
184
+ end
185
+ end
186
+
187
+ convert_to_type data, return_type
188
+ end
189
+
190
+ # Convert data to the given return type.
191
+ # @param [Object] data Data to be converted
192
+ # @param [String] return_type Return type
193
+ # @return [Mixed] Data in a particular type
194
+ def convert_to_type(data, return_type)
195
+ return nil if data.nil?
196
+ case return_type
197
+ when 'String'
198
+ data.to_s
199
+ when 'Integer'
200
+ data.to_i
201
+ when 'Float'
202
+ data.to_f
203
+ when 'BOOLEAN'
204
+ data == true
205
+ when 'DateTime'
206
+ # parse date time (expecting ISO 8601 format)
207
+ DateTime.parse data
208
+ when 'Date'
209
+ # parse date time (expecting ISO 8601 format)
210
+ Date.parse data
211
+ when 'Object'
212
+ # generic object (usually a Hash), return directly
213
+ data
214
+ when /\APage<(.+)>\z/
215
+ # e.g. Array<Pet>
216
+ sub_type = $1
217
+ items = data[:items].map { |item| convert_to_type(item, sub_type) }
218
+ Page.new(items, data[:__meta][:totalPages], data[:__meta][:totalElements], data[:__meta][:number],
219
+ data[:__meta][:size], data[:__meta][:nuberOfElements])
220
+ when /\AArray<(.+)>\z/
221
+ # e.g. Array<Pet>
222
+ sub_type = $1
223
+ data.map { |item| convert_to_type(item, sub_type) }
224
+ when /\AHash\<String, (.+)\>\z/
225
+ # e.g. Hash<String, Integer>
226
+ sub_type = $1
227
+ {}.tap do |hash|
228
+ data.each { |k, v| hash[k] = convert_to_type(v, sub_type) }
229
+ end
230
+ else
231
+ # models, e.g. Pet
232
+ Tradenity.const_get(return_type).new.tap do |model|
233
+ model.build_from_hash data
234
+ end
235
+ end
236
+ end
237
+
238
+ # Save response body into a file in (the defined) temporary folder, using the filename
239
+ # from the "Content-Disposition" header if provided, otherwise a random filename.
240
+ # The response body is written to the file in chunks in order to handle files which
241
+ # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby
242
+ # process can use.
243
+ #
244
+ # @see Configuration#temp_folder_path
245
+ def download_file(request)
246
+ tempfile = nil
247
+ encoding = nil
248
+ request.on_headers do |response|
249
+ content_disposition = response.headers['Content-Disposition']
250
+ if content_disposition && content_disposition =~ /filename=/i
251
+ filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1]
252
+ prefix = sanitize_filename(filename)
253
+ else
254
+ prefix = 'download-'
255
+ end
256
+ prefix = prefix + '-' unless prefix.end_with?('-')
257
+ encoding = response.body.encoding
258
+ tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding)
259
+ @tempfile = tempfile
260
+ end
261
+ request.on_body do |chunk|
262
+ chunk.force_encoding(encoding)
263
+ tempfile.write(chunk)
264
+ end
265
+ request.on_complete do |response|
266
+ tempfile.close
267
+ @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\
268
+ "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\
269
+ "will be deleted automatically with GC. It's also recommended to delete the temp file "\
270
+ "explicitly with `tempfile.delete`"
271
+ end
272
+ end
273
+
274
+ # Sanitize filename by removing path.
275
+ # e.g. ../../sun.gif becomes sun.gif
276
+ #
277
+ # @param [String] filename the filename to be sanitized
278
+ # @return [String] the sanitized filename
279
+ def sanitize_filename(filename)
280
+ filename.gsub(/.*[\/\\]/, '')
281
+ end
282
+
283
+ def build_request_url(path)
284
+ # Add leading and trailing slashes to path
285
+ path = "/#{path}".gsub(/\/+/, '/')
286
+ URI.encode(@config.base_url + path)
287
+ end
288
+
289
+ # Builds the HTTP request body
290
+ #
291
+ # @param [Hash] header_params Header parameters
292
+ # @param [Hash] form_params Query parameters
293
+ # @param [Object] body HTTP body (JSON/XML)
294
+ # @return [String] HTTP body data in the form of string
295
+ def build_request_body(header_params, form_params, body)
296
+ # http form
297
+ if header_params['Content-Type'] == 'application/x-www-form-urlencoded' ||
298
+ header_params['Content-Type'] == 'multipart/form-data'
299
+ data = {}
300
+ form_params.each do |key, value|
301
+ case value
302
+ when ::File, ::Array, nil
303
+ # let typhoeus handle File, Array and nil parameters
304
+ data[key] = value
305
+ else
306
+ data[key] = value.to_s
307
+ end
308
+ end
309
+ elsif body
310
+ data = body.is_a?(String) ? body : body.to_json
311
+ else
312
+ data = nil
313
+ end
314
+ data
315
+ end
316
+
317
+ # Update hearder and query params based on authentication settings.
318
+ #
319
+ # @param [Hash] header_params Header parameters
320
+ # @param [Hash] query_params Query parameters
321
+ # @param [String] auth_names Authentication scheme name
322
+ def update_params_for_auth!(header_params, query_params, auth_names)
323
+ Array(auth_names).each do |auth_name|
324
+ auth_setting = @config.auth_settings[auth_name]
325
+ next unless auth_setting
326
+ case auth_setting[:in]
327
+ when 'header' then header_params[auth_setting[:key]] = auth_setting[:value]
328
+ when 'query' then query_params[auth_setting[:key]] = auth_setting[:value]
329
+ else fail ArgumentError, 'Authentication token must be in `query` of `header`'
330
+ end
331
+ end
332
+ end
333
+
334
+ # Sets user agent in HTTP header
335
+ #
336
+ # @param [String] user_agent User agent (e.g. swagger-codegen/ruby/1.0.0)
337
+ def user_agent=(user_agent)
338
+ @user_agent = user_agent
339
+ @default_headers['User-Agent'] = @user_agent
340
+ end
341
+
342
+ # Return Accept header based on an array of accepts provided.
343
+ # @param [Array] accepts array for Accept
344
+ # @return [String] the Accept header (e.g. application/json)
345
+ def select_header_accept(accepts)
346
+ return nil if accepts.nil? || accepts.empty?
347
+ # use JSON when present, otherwise use all of the provided
348
+ json_accept = accepts.find { |s| json_mime?(s) }
349
+ json_accept || accepts.join(',')
350
+ end
351
+
352
+ # Return Content-Type header based on an array of content types provided.
353
+ # @param [Array] content_types array for Content-Type
354
+ # @return [String] the Content-Type header (e.g. application/json)
355
+ def select_header_content_type(content_types)
356
+ # use application/json by default
357
+ return 'application/json' if content_types.nil? || content_types.empty?
358
+ # use JSON when present, otherwise use the first one
359
+ json_content_type = content_types.find { |s| json_mime?(s) }
360
+ json_content_type || content_types.first
361
+ end
362
+
363
+ # Convert object (array, hash, object, etc) to JSON string.
364
+ # @param [Object] model object to be converted into JSON string
365
+ # @return [String] JSON string representation of the object
366
+ def object_to_http_body(model)
367
+ return model if model.nil? || model.is_a?(String)
368
+ local_body = nil
369
+ if model.is_a?(Array)
370
+ local_body = model.map { |m| object_to_hash(m) }
371
+ else
372
+ local_body = object_to_hash(model)
373
+ end
374
+ local_body.to_json
375
+ end
376
+
377
+ # Convert object(non-array) to hash.
378
+ # @param [Object] obj object to be converted into JSON string
379
+ # @return [String] JSON string representation of the object
380
+ def object_to_hash(obj)
381
+ if obj.respond_to?(:to_hash)
382
+ obj.to_hash
383
+ else
384
+ obj
385
+ end
386
+ end
387
+
388
+ # Build parameter value according to the given collection format.
389
+ # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi
390
+ def build_collection_param(param, collection_format)
391
+ case collection_format
392
+ when :csv
393
+ param.join(',')
394
+ when :ssv
395
+ param.join(' ')
396
+ when :tsv
397
+ param.join("\t")
398
+ when :pipes
399
+ param.join('|')
400
+ when :multi
401
+ # return the array directly as typhoeus will handle it as expected
402
+ param
403
+ else
404
+ fail "unknown collection format: #{collection_format.inspect}"
405
+ end
406
+ end
407
+ end
408
+ end
@@ -0,0 +1,36 @@
1
+ =begin
2
+ #Tradenity API
3
+
4
+ #Tradenity eCommerce Rest API
5
+
6
+ Contact: support@tradenity.com
7
+ Generated by: https://github.com/tradenity
8
+
9
+ =end
10
+
11
+ module Tradenity
12
+ class ApiError < StandardError
13
+ attr_reader :code, :response_headers, :response_body
14
+
15
+ # Usage examples:
16
+ # ApiError.new
17
+ # ApiError.new("message")
18
+ # ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
19
+ # ApiError.new(:code => 404, :message => "Not Found")
20
+ def initialize(arg = nil)
21
+ if arg.is_a? Hash
22
+ if arg.key?(:message) || arg.key?('message')
23
+ super(arg[:message] || arg['message'])
24
+ else
25
+ super arg
26
+ end
27
+
28
+ arg.each do |k, v|
29
+ instance_variable_set "@#{k}", v
30
+ end
31
+ else
32
+ super arg
33
+ end
34
+ end
35
+ end
36
+ end