easypost 4.0.0 → 4.1.2

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4033b69b8c91126ab87ed8a16c3b5dd8bd7b4b06b9e7cc4011fe478163244a3a
4
- data.tar.gz: 554e850ea8107cd0d8de3efca5c0ed18834c7b51c5c437ca9e6c4f8d197489a2
3
+ metadata.gz: 2b2de1c12852ffd59083d6ee132f2071577e7ff774f77cb515b444f75eaf86fc
4
+ data.tar.gz: 98b1d4bce4a86d9cdf3480f91e818dc362af2963e38f9bccb434b557aebf6bcc
5
5
  SHA512:
6
- metadata.gz: 77335abc417c0cf3d1af97d9b4941b00f8dec6400282d0f4f25a3408c47b82eaa5f8a8de6564f250e6a985f3261c296eb22d535eed3d04cc5c7a2716c5239352
7
- data.tar.gz: 27cc114d89dddec6d2bf7862cd0f15c8d875f739a806a1589ca2626fc61ed9387ee5602d373c85902d6fc8908fe266df347d5d7409a4e9af42cb0091e5791690
6
+ metadata.gz: 97fceef78d0d5706cd0ddb553f6da95ad5a27fe2491069f2eb416dafcb296a158d6e03bab6232ef0efe63f7503a256830635847288e99f17129920adade55eae
7
+ data.tar.gz: 2d3a0058d85435a3b743ef9f1b3f21e42bd77bf5cf830f5522794369f27315a9ca673f65fb9f3900df718668d2207ed63c295b7f36f415979cd53dae8cfe0110
data/.gitignore CHANGED
@@ -28,3 +28,4 @@ Icon
28
28
  .Spotlight-V100
29
29
  .Trashes
30
30
  vendor/
31
+ .env
data/CHANGELOG.md CHANGED
@@ -1,225 +1,239 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## v4.1.2 (2022-03-16)
4
+
5
+ - Rolls back the original connection behavior of establishing a new connection for every request (restores previous expectations for multithreaded implementations)
6
+
7
+ ## v4.1.1 (2022-03-14)
8
+
9
+ - Fixes a bug that prematurely closed connections when using multithreading by wrapping requests in a mutex (closes #148)
10
+
11
+ ## v4.1.0 (2022-03-09)
12
+
13
+ - Adds support for custom client connections (#142)
14
+ - Reduces memory usage by reusing connections
15
+ - Extends all objects with `Enumerable` allowing for iterator patterns (#143)
16
+
3
17
  ## v4.0.0 (2022-02-25)
4
18
 
5
- * Bumps minimum Ruby version from `2.2` to `2.5`
6
- * Bumps dev dependencies
7
- * Documents each interface of the project in code
8
- * Overhauls the test suite with full coverage
9
- * Introduces `Rubocop` and lints the entire project
10
- * Removes the unusable `Print` and `PrintJob` objects
11
- * Removes deprecated and unusable `stamp_and_barcode_by_reference` method on the Batch object
12
- * Explicitly returns an error of "not implemented" for `Rate.all` and `Parcel.all`
13
- * Removes the `Shipment.get_rates` function as shipments already contain rates. If you need to get new rates for a shipment, use the `Shipment.regenerate_rates` function instead
14
- * Removes the parameters from `Address.verify` as they are unusable
15
- * Removes the deprecated `http_status` property of the `EasyPost::Error` object as it was replaced with `status`
16
- * Fixes a bug that would append an extra `id` field to each retrieved object
17
- * Various other small improvements and bug fixes
19
+ - Bumps minimum Ruby version from `2.2` to `2.5`
20
+ - Bumps dev dependencies
21
+ - Documents each interface of the project in code
22
+ - Overhauls the test suite with full coverage
23
+ - Introduces `Rubocop` and lints the entire project
24
+ - Removes the unusable `Print` and `PrintJob` objects
25
+ - Removes deprecated and unusable `stamp_and_barcode_by_reference` method on the Batch object
26
+ - Explicitly returns an error of "not implemented" for `Rate.all` and `Parcel.all`
27
+ - Removes the `Shipment.get_rates` function as shipments already contain rates. If you need to get new rates for a shipment, use the `Shipment.regenerate_rates` function instead
28
+ - Removes the parameters from `Address.verify` as they are unusable
29
+ - Removes the deprecated `http_status` property of the `EasyPost::Error` object as it was replaced with `status`
30
+ - Fixes a bug that would append an extra `id` field to each retrieved object
31
+ - Various other small improvements and bug fixes
18
32
 
19
33
  ## v3.5.0 (2021-12-06)
20
34
 
21
- * Adds the `update_brand` method to the user object (closes #122)
35
+ - Adds the `update_brand` method to the user object (closes #122)
22
36
 
23
37
  ## v3.4.0 (2021-07-13)
24
38
 
25
- * Removed deprecated `Item` object
26
- * Sorted EasyPost Resources list
27
- * Remove 2015-vintage experimental `all_updated` method on Tracker
28
- * Fixes API key retrieval (#120, thanks @andychongyz)
29
- * Adds `regenerate_rates` method for new rerate API
30
- * Adds `deconstruct_keys` method to allow for pattern matching on EasyPost objects
39
+ - Removed deprecated `Item` object
40
+ - Sorted EasyPost Resources list
41
+ - Remove 2015-vintage experimental `all_updated` method on Tracker
42
+ - Fixes API key retrieval (#120, thanks @andychongyz)
43
+ - Adds `regenerate_rates` method for new rerate API
44
+ - Adds `deconstruct_keys` method to allow for pattern matching on EasyPost objects
31
45
 
32
46
  ## v3.3.0 (2021-06-10)
33
47
 
34
- * Adds `SmartRate` functionality to the `Shipments` object (available by calling `get_smartrates` on a shipment)
35
- * Fix bug where `EasyPost::CarrierAccount.types` was hitting the wrong endpoint
48
+ - Adds `SmartRate` functionality to the `Shipments` object (available by calling `get_smartrates` on a shipment)
49
+ - Fix bug where `EasyPost::CarrierAccount.types` was hitting the wrong endpoint
36
50
 
37
51
  ## v3.2.0 (2021-01-14)
38
52
 
39
- * Replace Travis CI with Github Actions
40
- * Add Ruby 3.0 to supported platforms (#110; thanks @maxwell)
53
+ - Replace Travis CI with Github Actions
54
+ - Add Ruby 3.0 to supported platforms (#110; thanks @maxwell)
41
55
 
42
56
  ## v3.1.5 (2020-12-16)
43
57
 
44
- * Fix attribute lookup when manually constructing objects (#105; thanks @drewtempelmeyer)
45
- * Flatten class names and clean up some other style issues
46
- * Fix `EasyPost::Address.create_and_verify`, broken since 3.1.0 (#108; thanks @rajbirverma)
58
+ - Fix attribute lookup when manually constructing objects (#105; thanks @drewtempelmeyer)
59
+ - Flatten class names and clean up some other style issues
60
+ - Fix `EasyPost::Address.create_and_verify`, broken since 3.1.0 (#108; thanks @rajbirverma)
47
61
 
48
62
  ## v3.1.4 (2020-09-29)
49
63
 
50
- * Don't modify params passed into Address#create (#78; thanks @TheRusskiy)
51
- * Don't modify `carriers` and `services` parameters to `Shipment.lowest_rate` (#71 / #103, thanks @vladvinnikov and @jurisgalang)
52
- * When constructing an easypost object, convert the key to a string (#102; thanks @Geesu)
53
- * Expose the raw HTTP response as `#http_body` on `EasyPost::Error` objects (#101; thanks @Geesu)
64
+ - Don't modify params passed into Address#create (#78; thanks @TheRusskiy)
65
+ - Don't modify `carriers` and `services` parameters to `Shipment.lowest_rate` (#71 / #103, thanks @vladvinnikov and @jurisgalang)
66
+ - When constructing an easypost object, convert the key to a string (#102; thanks @Geesu)
67
+ - Expose the raw HTTP response as `#http_body` on `EasyPost::Error` objects (#101; thanks @Geesu)
54
68
 
55
69
  ## v3.1.3 (2020-06-26)
56
70
 
57
- * Fix bug causing Authorization header to be included in User-Agent header. All users must upgrade.
71
+ - Fix bug causing Authorization header to be included in User-Agent header. All users must upgrade.
58
72
 
59
73
  ## v3.1.2 (2020-06-24)
60
74
 
61
- * Bad gem push. New version required.
75
+ - Bad gem push. New version required.
62
76
 
63
77
  ## v3.1.1 (2020-06-23)
64
78
 
65
- * Fix bug where EasyPost.http_config was invalid when not explicitly initialized.
79
+ - Fix bug where EasyPost.http_config was invalid when not explicitly initialized.
66
80
 
67
81
  ## v3.1.0 (2020-06-23)
68
82
 
69
- * Add Shipment Invoice and Refund Report
70
- * Remove dependencies on `RestClient` and `MultiJson`
71
- * Remove some deprecated endpoints
83
+ - Add Shipment Invoice and Refund Report
84
+ - Remove dependencies on `RestClient` and `MultiJson`
85
+ - Remove some deprecated endpoints
72
86
 
73
87
  ## v3.0.1 (2018-05-17)
74
88
 
75
- * Enforce TLS certificate validity by default
89
+ - Enforce TLS certificate validity by default
76
90
 
77
91
  ## v3.0.0 (2018-02-15)
78
92
 
79
- * Require use of ruby ~> 2.0 and TLSv1.2
93
+ - Require use of ruby ~> 2.0 and TLSv1.2
80
94
 
81
95
  ## v2.7.3 (2018-02-05)
82
96
 
83
- * Fix bug with introduced around certain JSON objects with IDs (thanks vladvinnikov!)
97
+ - Fix bug with introduced around certain JSON objects with IDs (thanks vladvinnikov!)
84
98
 
85
99
  ## v2.7.2 (2018-02-01)
86
100
 
87
- * Removed unused and unsupported code paths for Container model
88
- * Removed unused and unsupported code path for Stamp and Barcode methods on the Shipment model
89
- * Fixed a bug with non-model JSON object with an "id" key being treated as models and raising errors
101
+ - Removed unused and unsupported code paths for Container model
102
+ - Removed unused and unsupported code path for Stamp and Barcode methods on the Shipment model
103
+ - Fixed a bug with non-model JSON object with an "id" key being treated as models and raising errors
90
104
 
91
105
  ## v2.7.1 (2017-05-25)
92
106
 
93
- * Allow reports to be retrieved without passing a type
107
+ - Allow reports to be retrieved without passing a type
94
108
 
95
109
  ## v2.7.0 (2017-04-04)
96
110
 
97
- * Changed Report CRUD signatures. requires report type to be passed
111
+ - Changed Report CRUD signatures. requires report type to be passed
98
112
 
99
113
  ## v2.6.2 (2017-02-14)
100
114
 
101
- * Added get_rates method for Orders
115
+ - Added get_rates method for Orders
102
116
 
103
117
  ## v2.6.1 (2017-01-19)
104
118
 
105
- * Updated create method for ScanForms
119
+ - Updated create method for ScanForms
106
120
 
107
121
  ## v2.6.0 (2017-01-17)
108
122
 
109
- * Add basic CRUD methods for Webhooks
123
+ - Add basic CRUD methods for Webhooks
110
124
 
111
125
  ## v2.5.0 (2016-12-19)
112
126
 
113
- * Add prefixes to report in utils
127
+ - Add prefixes to report in utils
114
128
 
115
129
  ## v2.4.0 (2016-12-08)
116
130
 
117
- * Add report resource to ruby client
131
+ - Add report resource to ruby client
118
132
 
119
133
  ## v2.3.0 (2016-11-25)
120
134
 
121
- * Updated dependencies to allow rest-client 2.0.0 and above
135
+ - Updated dependencies to allow rest-client 2.0.0 and above
122
136
 
123
137
  ## v2.2.0 (2016-07-260
124
138
 
125
- * Added standalone Insurance model
139
+ - Added standalone Insurance model
126
140
 
127
141
  ## v2.1.11 (2016-02-04)
128
142
 
129
- * Allowed user creation for top-level users
143
+ - Allowed user creation for top-level users
130
144
 
131
145
  ## v2.1.10 (2015-12-23)
132
146
 
133
- * Added verify and verify_strict params to Address.create
134
- * Added Tracker.create_list and Tracker.all_updated for working with large
135
- numbers of Trackers.
147
+ - Added verify and verify_strict params to Address.create
148
+ - Added Tracker.create_list and Tracker.all_updated for working with large
149
+ numbers of Trackers.
136
150
 
137
151
  ## v2.1.9 (2015-11-04)
138
152
 
139
- * Added new tests for Tracker.all
140
- * Updated some old examples
153
+ - Added new tests for Tracker.all
154
+ - Updated some old examples
141
155
 
142
156
  ## v2.1.8 (2015-10-21)
143
157
 
144
- * Added Cancel method for Pickups (thanks Ramie Blatt!)
158
+ - Added Cancel method for Pickups (thanks Ramie Blatt!)
145
159
 
146
160
  ## v2.1.7 (2015-10-05)
147
161
 
148
- * Fixed Address.create_and_verify and changed how errors are raised (thanks Dimitri Roche!)
149
- * Require newer version of the multi_json package
162
+ - Fixed Address.create_and_verify and changed how errors are raised (thanks Dimitri Roche!)
163
+ - Require newer version of the multi_json package
150
164
 
151
165
  ## v2.1.6 (2015-06-10)
152
166
 
153
- * Added Address message accessor for backwards compatability
167
+ - Added Address message accessor for backwards compatability
154
168
 
155
169
  ## v2.1.5 (2015-06-10)
156
170
 
157
- * Removed Address.message
171
+ - Removed Address.message
158
172
 
159
173
  ## v2.1.4 (2015-06-03)
160
174
 
161
- * Add Printer and PrintJob resources.
175
+ - Add Printer and PrintJob resources.
162
176
 
163
177
  ## v2.1.3 (2015-04-30)
164
178
 
165
- * Bux fix, EasyPost::Errors no longer break with a nil json body.
179
+ - Bux fix, EasyPost::Errors no longer break with a nil json body.
166
180
 
167
181
  ## v2.1.2 (2015-04-29)
168
182
 
169
- * EasyPost::Errors now correctly parse field errors and error codes.
183
+ - EasyPost::Errors now correctly parse field errors and error codes.
170
184
 
171
185
  ## v2.1.1 (2015-04-15)
172
186
 
173
- * CarrierAccount will now correctly save in-place modifications to credentials
174
- * Nested variables should now be saved correctly across all models
175
- * Fixed version numbering confusion (the previous version was 2.0.15, not 2.1.0)
187
+ - CarrierAccount will now correctly save in-place modifications to credentials
188
+ - Nested variables should now be saved correctly across all models
189
+ - Fixed version numbering confusion (the previous version was 2.0.15, not 2.1.0)
176
190
 
177
191
  ## v2.0.15 (2015-04-15)
178
192
 
179
- * Added tracker to shipment buy response
180
- * Updated tracker tests
193
+ - Added tracker to shipment buy response
194
+ - Updated tracker tests
181
195
 
182
196
  ## v2.0.14 (2015-04-15)
183
197
 
184
- * Added User and CarrierAccount models with CRUD functionality
198
+ - Added User and CarrierAccount models with CRUD functionality
185
199
 
186
200
  ## v2.0.13 (2014-10-30)
187
201
 
188
- * Added Pickup, PickupRate resources.
189
- * Added ability to pass api_key to a few resources that were missing it.
202
+ - Added Pickup, PickupRate resources.
203
+ - Added ability to pass api_key to a few resources that were missing it.
190
204
 
191
205
  ## v2.0.12 (2014-07-07)
192
206
 
193
- * Added Item, Container, and Order resources.
194
- * Fixed and added a lot of tests.
207
+ - Added Item, Container, and Order resources.
208
+ - Fixed and added a lot of tests.
195
209
 
196
210
  ## v2.0.11 (2013-12-16)
197
211
 
198
- * Added Event.receive method for parsing events sent by webhook.
199
- * Fixed tests to account for the tracking code returning and array of details instead of a Hash
212
+ - Added Event.receive method for parsing events sent by webhook.
213
+ - Fixed tests to account for the tracking code returning and array of details instead of a Hash
200
214
 
201
215
  ## v2.0.10 (2013-10-03)
202
216
 
203
- * API Addition: Event resource added for webhook consumption.
217
+ - API Addition: Event resource added for webhook consumption.
204
218
 
205
219
  ## v2.0.9 (2013-09-19)
206
220
 
207
- * Interface Change: Changed batch.scan_form to batch.create_scan_form to support the ability to refer to scan forms associated to batches.
221
+ - Interface Change: Changed batch.scan_form to batch.create_scan_form to support the ability to refer to scan forms associated to batches.
208
222
 
209
223
  ## v2.0.3 (2013-07-31)
210
224
 
211
- * API Addition: Tracker resource added. Trackers can be used to register any tracking code with EasyPost webhooks.
225
+ - API Addition: Tracker resource added. Trackers can be used to register any tracking code with EasyPost webhooks.
212
226
 
213
227
  ## v2.0.2 (2013-07-23)
214
228
 
215
- * API Addition: Shipment.track_with_code returns tracking details for any tracking code.
229
+ - API Addition: Shipment.track_with_code returns tracking details for any tracking code.
216
230
 
217
231
  ## v2.0.1 (2013-07-07)
218
232
 
219
- * API Addition: Address.create_and_verify returns a verified address in one step.
220
- * API Addition: Shipment.label forces the creation of additional label formats (pdf, epl2, zpl).
221
- * API Addition: Shipment.insure purchases insurance for a shipment.
222
- * Library Update: Added the ability to negatively filter carriers and services with Shipment.lowest_rate (e.g. '!usps').
233
+ - API Addition: Address.create_and_verify returns a verified address in one step.
234
+ - API Addition: Shipment.label forces the creation of additional label formats (pdf, epl2, zpl).
235
+ - API Addition: Shipment.insure purchases insurance for a shipment.
236
+ - Library Update: Added the ability to negatively filter carriers and services with Shipment.lowest_rate (e.g. '!usps').
223
237
 
224
238
  ## v2.0.0 (2013-06-25)
225
239
 
data/README.md CHANGED
@@ -103,3 +103,54 @@ Up-to-date documentation at: https://easypost.com/docs
103
103
  # Run tests (coverage is generated on a successful test suite run)
104
104
  EASYPOST_TEST_API_KEY=123... EASYPOST_PROD_API_KEY=123... bundle exec rspec
105
105
  ```
106
+
107
+ ## Custom connections
108
+
109
+ Set `EasyPost.default_connection` to an object that responds to `call(method, path, api_key = nil, body = nil)`
110
+
111
+ ### Faraday
112
+
113
+ ```ruby
114
+ require 'faraday'
115
+ require 'faraday/response/logger'
116
+ require 'logger'
117
+
118
+ EasyPost.default_connection = lambda do |method, path, api_key = nil, body = nil|
119
+ Faraday
120
+ .new(url: EasyPost.api_base, headers: EasyPost.default_headers) { |builder|
121
+ builder.use Faraday::Response::Logger, Logger.new(STDOUT), {bodies: true, headers: true}
122
+ builder.adapter :net_http
123
+ }
124
+ .public_send(method, path) { |request|
125
+ request.headers['Authorization'] = EasyPost.authorization(api_key)
126
+ request.body = JSON.dump(EasyPost::Util.objects_to_ids(body)) if body
127
+ }.yield_self { |response|
128
+ EasyPost.parse_response(
129
+ status: response.status,
130
+ body: response.body,
131
+ json: response.headers['Content-Type'].start_with?('application/json'),
132
+ )
133
+ }
134
+ end
135
+ ```
136
+
137
+ ### Typhoeus
138
+
139
+ ```ruby
140
+ require 'typhoeus'
141
+
142
+ EasyPost.default_connection = lambda do |method, path, api_key = nil, body = nil|
143
+ Typhoeus.public_send(
144
+ method,
145
+ File.join(EasyPost.api_base, path),
146
+ headers: EasyPost.default_headers.merge('Authorization' => EasyPost.authorization(api_key)),
147
+ body: body.nil? ? nil : JSON.dump(EasyPost::Util.objects_to_ids(body)),
148
+ ).yield_self { |response|
149
+ EasyPost.parse_response(
150
+ status: response.code,
151
+ body: response.body,
152
+ json: response.headers['Content-Type'].start_with?('application/json'),
153
+ )
154
+ }
155
+ end
156
+ ```
data/VERSION CHANGED
@@ -1 +1 @@
1
- 4.0.0
1
+ 4.1.2
@@ -0,0 +1,61 @@
1
+ # frozen_string_literal: true
2
+
3
+ EasyPost::Connection = Struct.new(:uri, :config, keyword_init: true) do
4
+ # Make an HTTP request with Ruby's {Net::HTTP}
5
+ #
6
+ # @param method [Symbol] the HTTP Verb (get, method, put, post, etc.)
7
+ # @param path [String] URI path of the resource
8
+ # @param requested_api_key [String] ({EasyPost.api_key}) key set Authorization header.
9
+ # @param body [String] (nil) body of the request
10
+ # @raise [EasyPost::Error] if the response has a non-2xx status code
11
+ # @return [Hash] JSON object parsed from the response body
12
+ def call(method, path, api_key = nil, body = nil)
13
+ connection =
14
+ if config[:proxy]
15
+ proxy_uri = URI(config[:proxy])
16
+ Net::HTTP.new(
17
+ uri.host,
18
+ uri.port,
19
+ proxy_uri.host,
20
+ proxy_uri.port,
21
+ proxy_uri.user,
22
+ proxy_uri.password,
23
+ )
24
+ else
25
+ Net::HTTP.new(uri.host, uri.port)
26
+ end
27
+
28
+ connection.use_ssl = true
29
+
30
+ config.each do |name, value|
31
+ # Discrepancies between RestClient and Net::HTTP.
32
+ case name
33
+ when :verify_ssl
34
+ name = :verify_mode
35
+ when :timeout
36
+ name = :read_timeout
37
+ end
38
+
39
+ # Handled in the creation of the client.
40
+ if name == :proxy
41
+ next
42
+ end
43
+
44
+ connection.public_send("#{name}=", value)
45
+ end
46
+
47
+ request = Net::HTTP.const_get(method.capitalize).new(path)
48
+ request.body = JSON.dump(EasyPost::Util.objects_to_ids(body)) if body
49
+
50
+ EasyPost.default_headers.each_pair { |h, v| request[h] = v }
51
+ request['Authorization'] = EasyPost.authorization(api_key) if api_key
52
+
53
+ response = connection.request(request)
54
+
55
+ EasyPost.parse_response(
56
+ status: response.code.to_i,
57
+ body: response.body,
58
+ json: response['Content-Type'].start_with?('application/json'),
59
+ )
60
+ end
61
+ end
@@ -2,6 +2,8 @@
2
2
 
3
3
  # The Resource object is extended by each EasyPost object.
4
4
  class EasyPost::Resource < EasyPost::EasyPostObject
5
+ extend Enumerable
6
+
5
7
  # The class name of an EasyPost object.
6
8
  def self.class_name
7
9
  camel = name.split('::')[-1]
@@ -46,6 +48,18 @@ class EasyPost::Resource < EasyPost::EasyPostObject
46
48
  EasyPost::Util.convert_to_easypost_object(response, api_key)
47
49
  end
48
50
 
51
+ def self.each(filters = {}, api_key = EasyPost.api_key, &block)
52
+ return to_enum(:each, filters, api_key) unless block_given?
53
+
54
+ loop do
55
+ page, has_more = all(filters, api_key).values
56
+ last = page.each(&block).last
57
+ break if page.empty? || !has_more
58
+
59
+ filters[:before_id] = last.id
60
+ end
61
+ end
62
+
49
63
  # Retrieve an EasyPost object.
50
64
  def self.retrieve(id, api_key = nil)
51
65
  instance = new(id, api_key)
data/lib/easypost.rb CHANGED
@@ -9,6 +9,7 @@ require 'easypost/util'
9
9
  require 'easypost/object'
10
10
  require 'easypost/resource'
11
11
  require 'easypost/error'
12
+ require 'easypost/connection'
12
13
 
13
14
  # Resources
14
15
  require 'easypost/address'
@@ -37,32 +38,42 @@ require 'easypost/user'
37
38
  require 'easypost/webhook'
38
39
 
39
40
  module EasyPost
40
- @api_key = nil
41
- @api_base = 'https://api.easypost.com'
41
+ DEFAULT_API_BASE = 'https://api.easypost.com'
42
+ DEFAULT_USER_AGENT = "EasyPost/v2 RubyClient/#{EasyPost::VERSION} Ruby/#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
42
43
 
43
- # Set the ApiKey.
44
- def self.api_key=(api_key)
45
- @api_key = api_key
44
+ class << self
45
+ attr_accessor :api_key, :api_base
46
+ attr_writer :default_connection
46
47
  end
47
48
 
48
- # Get the ApiKey.
49
- def self.api_key
50
- @api_key
49
+ self.api_base = DEFAULT_API_BASE
50
+
51
+ def self.default_headers
52
+ @default_headers ||= {
53
+ 'Content-Type' => 'application/json',
54
+ 'User-Agent' => EasyPost::DEFAULT_USER_AGENT,
55
+ }
51
56
  end
52
57
 
53
- # Set the API base.
54
- def self.api_base=(api_base)
55
- @api_base = api_base
58
+ def self.default_connection
59
+ @default_connection ||= EasyPost::Connection.new(
60
+ uri: URI(api_base),
61
+ config: http_config,
62
+ )
56
63
  end
57
64
 
58
- # Get the API base.
59
- def self.api_base
60
- @api_base
65
+ def self.authorization(key)
66
+ "Basic #{Base64.strict_encode64("#{key}:")}"
61
67
  end
62
68
 
63
69
  # Reset the HTTP config.
64
70
  def self.reset_http_config
65
- @http_config = {
71
+ http_config.clear
72
+ self.default_connection = nil
73
+ end
74
+
75
+ def self.default_http_config
76
+ http_config = {
66
77
  timeout: 60,
67
78
  open_timeout: 30,
68
79
  verify_ssl: OpenSSL::SSL::VERIFY_PEER,
@@ -70,89 +81,60 @@ module EasyPost
70
81
 
71
82
  ruby_version = Gem::Version.new(RUBY_VERSION)
72
83
  if ruby_version >= Gem::Version.new('2.5.0')
73
- @http_config[:min_version] = OpenSSL::SSL::TLS1_2_VERSION
84
+ http_config[:min_version] = OpenSSL::SSL::TLS1_2_VERSION
74
85
  else
75
- @http_config[:ssl_version] = :TLSv1_2 # rubocop:disable Naming/VariableNumber
86
+ http_config[:ssl_version] = :TLSv1_2 # rubocop:disable Naming/VariableNumber
76
87
  end
77
88
 
78
- @http_config
89
+ http_config
79
90
  end
80
91
 
81
92
  # Get the HTTP config.
82
93
  def self.http_config
83
- @http_config ||= reset_http_config
94
+ @http_config ||= default_http_config
84
95
  end
85
96
 
86
97
  # Set the HTTP config.
87
98
  def self.http_config=(http_config_params)
88
99
  http_config.merge!(http_config_params)
100
+
101
+ self.default_connection = nil
89
102
  end
90
103
 
91
104
  # Create an EasyPost Client.
92
- def self.make_client(uri)
93
- client = if http_config[:proxy]
94
- proxy_uri = URI(http_config[:proxy])
95
- Net::HTTP.new(
96
- uri.host,
97
- uri.port,
98
- proxy_uri.host,
99
- proxy_uri.port,
100
- proxy_uri.user,
101
- proxy_uri.password,
102
- )
103
- else
104
- Net::HTTP.new(uri.host, uri.port)
105
- end
106
- client.use_ssl = true
107
-
108
- http_config.each do |name, value|
109
- # Discrepancies between RestClient and Net::HTTP.
110
- case name
111
- when :verify_ssl
112
- name = :verify_mode
113
- when :timeout
114
- name = :read_timeout
115
- end
116
-
117
- # Handled in the creation of the client.
118
- if name == :proxy
119
- next
120
- end
121
-
122
- client.send("#{name}=", value)
123
- end
124
-
125
- client
105
+ #
106
+ # @deprecated
107
+ def self.make_client(url)
108
+ EasyPost::Connection.new(uri: URI(url), config: http_config).create
126
109
  end
127
110
 
128
- # Make an HTTP request.
111
+ # Make an HTTP request against the {default_connection}
112
+ #
113
+ # @param method [Symbol] the HTTP Verb (get, method, put, post, etc.)
114
+ # @param path [String] URI path of the resource
115
+ # @param requested_api_key [String] ({EasyPost.api_key}) key set Authorization header.
116
+ # @param body [Object] (nil) object to be dumped to JSON
117
+ # @raise [EasyPost::Error] if the response has a non-2xx status code
118
+ # @return [Hash] JSON object parsed from the response body
129
119
  def self.make_request(method, path, api_key = nil, body = nil)
130
- client = make_client(URI(@api_base))
131
-
132
- request = Net::HTTP.const_get(method.capitalize).new(path)
133
- if body
134
- request.body = JSON.dump(EasyPost::Util.objects_to_ids(body))
135
- end
136
-
137
- request['Content-Type'] = 'application/json'
138
- request['User-Agent'] = "EasyPost/v2 RubyClient/#{VERSION} Ruby/#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL}"
139
- if api_key ||= @api_key
140
- request['Authorization'] = "Basic #{Base64.strict_encode64("#{api_key}:")}"
141
- end
142
-
143
- response = client.request(request)
120
+ default_connection.call(method, path, api_key || EasyPost.api_key, body)
121
+ end
144
122
 
145
- if (400..599).include? response.code.to_i
146
- error = JSON.parse(response.body)['error']
147
- raise EasyPost::Error.new(error['message'], response.code.to_i, error['code'], error['errors'], response.body)
123
+ def self.parse_response(status:, body:, json:)
124
+ if status >= 400
125
+ error = JSON.parse(body)['error']
126
+
127
+ raise EasyPost::Error.new(
128
+ error['message'],
129
+ status,
130
+ error['code'],
131
+ error['errors'],
132
+ body,
133
+ )
148
134
  end
149
135
 
150
- if response['Content-Type'].include? 'application/json'
151
- JSON.parse(response.body)
152
- else
153
- response.body
154
- end
136
+ json ? JSON.parse(body) : body
155
137
  rescue JSON::ParserError
156
- raise "Invalid response object from API, unable to decode.\n#{response.body}"
138
+ raise "Invalid response object from API, unable to decode.\n#{body}"
157
139
  end
158
140
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: easypost
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.0.0
4
+ version: 4.1.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - EasyPost Developers
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2022-02-25 00:00:00.000000000 Z
11
+ date: 2022-03-16 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: pry
@@ -163,6 +163,7 @@ files:
163
163
  - lib/easypost/brand.rb
164
164
  - lib/easypost/carrier_account.rb
165
165
  - lib/easypost/carrier_type.rb
166
+ - lib/easypost/connection.rb
166
167
  - lib/easypost/customs_info.rb
167
168
  - lib/easypost/customs_item.rb
168
169
  - lib/easypost/error.rb