easypost 4.0.0 → 4.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4033b69b8c91126ab87ed8a16c3b5dd8bd7b4b06b9e7cc4011fe478163244a3a
4
- data.tar.gz: 554e850ea8107cd0d8de3efca5c0ed18834c7b51c5c437ca9e6c4f8d197489a2
3
+ metadata.gz: c1b008c0a117ef6b7ad4082b45e0ca94b723e14601b24c8732da23166acb1996
4
+ data.tar.gz: 52057de46c2642e4896c81a1d866e0b47fe4ec20fbad91ca5d0814a7c9fa6ea1
5
5
  SHA512:
6
- metadata.gz: 77335abc417c0cf3d1af97d9b4941b00f8dec6400282d0f4f25a3408c47b82eaa5f8a8de6564f250e6a985f3261c296eb22d535eed3d04cc5c7a2716c5239352
7
- data.tar.gz: 27cc114d89dddec6d2bf7862cd0f15c8d875f739a806a1589ca2626fc61ed9387ee5602d373c85902d6fc8908fe266df347d5d7409a4e9af42cb0091e5791690
6
+ metadata.gz: 41f82883c0831354a2c517910a35b6fdb0a3335ec3e86fb7038ffd2660b56523819c2181f45b97814445fb62781a749009cc0a936a9011a80a93600817a1ecfc
7
+ data.tar.gz: 7000cae174dd8b99bc5e6608a922d68692f1586afe370c2daa97ee854c0540766ada8cb84fa53c1d3ae389c23a1fbf813d046bf91519c0262bd5226565f6e535
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,231 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## v4.1.0 (2022-03-09)
4
+
5
+ - Adds support for custom client connections (#142)
6
+ - Reduces memory usage by reusing connections
7
+ - Extends all objects with `Enumerable` allowing for iterator patterns (#143)
8
+
3
9
  ## v4.0.0 (2022-02-25)
4
10
 
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
11
+ - Bumps minimum Ruby version from `2.2` to `2.5`
12
+ - Bumps dev dependencies
13
+ - Documents each interface of the project in code
14
+ - Overhauls the test suite with full coverage
15
+ - Introduces `Rubocop` and lints the entire project
16
+ - Removes the unusable `Print` and `PrintJob` objects
17
+ - Removes deprecated and unusable `stamp_and_barcode_by_reference` method on the Batch object
18
+ - Explicitly returns an error of "not implemented" for `Rate.all` and `Parcel.all`
19
+ - 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
20
+ - Removes the parameters from `Address.verify` as they are unusable
21
+ - Removes the deprecated `http_status` property of the `EasyPost::Error` object as it was replaced with `status`
22
+ - Fixes a bug that would append an extra `id` field to each retrieved object
23
+ - Various other small improvements and bug fixes
18
24
 
19
25
  ## v3.5.0 (2021-12-06)
20
26
 
21
- * Adds the `update_brand` method to the user object (closes #122)
27
+ - Adds the `update_brand` method to the user object (closes #122)
22
28
 
23
29
  ## v3.4.0 (2021-07-13)
24
30
 
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
31
+ - Removed deprecated `Item` object
32
+ - Sorted EasyPost Resources list
33
+ - Remove 2015-vintage experimental `all_updated` method on Tracker
34
+ - Fixes API key retrieval (#120, thanks @andychongyz)
35
+ - Adds `regenerate_rates` method for new rerate API
36
+ - Adds `deconstruct_keys` method to allow for pattern matching on EasyPost objects
31
37
 
32
38
  ## v3.3.0 (2021-06-10)
33
39
 
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
40
+ - Adds `SmartRate` functionality to the `Shipments` object (available by calling `get_smartrates` on a shipment)
41
+ - Fix bug where `EasyPost::CarrierAccount.types` was hitting the wrong endpoint
36
42
 
37
43
  ## v3.2.0 (2021-01-14)
38
44
 
39
- * Replace Travis CI with Github Actions
40
- * Add Ruby 3.0 to supported platforms (#110; thanks @maxwell)
45
+ - Replace Travis CI with Github Actions
46
+ - Add Ruby 3.0 to supported platforms (#110; thanks @maxwell)
41
47
 
42
48
  ## v3.1.5 (2020-12-16)
43
49
 
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)
50
+ - Fix attribute lookup when manually constructing objects (#105; thanks @drewtempelmeyer)
51
+ - Flatten class names and clean up some other style issues
52
+ - Fix `EasyPost::Address.create_and_verify`, broken since 3.1.0 (#108; thanks @rajbirverma)
47
53
 
48
54
  ## v3.1.4 (2020-09-29)
49
55
 
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)
56
+ - Don't modify params passed into Address#create (#78; thanks @TheRusskiy)
57
+ - Don't modify `carriers` and `services` parameters to `Shipment.lowest_rate` (#71 / #103, thanks @vladvinnikov and @jurisgalang)
58
+ - When constructing an easypost object, convert the key to a string (#102; thanks @Geesu)
59
+ - Expose the raw HTTP response as `#http_body` on `EasyPost::Error` objects (#101; thanks @Geesu)
54
60
 
55
61
  ## v3.1.3 (2020-06-26)
56
62
 
57
- * Fix bug causing Authorization header to be included in User-Agent header. All users must upgrade.
63
+ - Fix bug causing Authorization header to be included in User-Agent header. All users must upgrade.
58
64
 
59
65
  ## v3.1.2 (2020-06-24)
60
66
 
61
- * Bad gem push. New version required.
67
+ - Bad gem push. New version required.
62
68
 
63
69
  ## v3.1.1 (2020-06-23)
64
70
 
65
- * Fix bug where EasyPost.http_config was invalid when not explicitly initialized.
71
+ - Fix bug where EasyPost.http_config was invalid when not explicitly initialized.
66
72
 
67
73
  ## v3.1.0 (2020-06-23)
68
74
 
69
- * Add Shipment Invoice and Refund Report
70
- * Remove dependencies on `RestClient` and `MultiJson`
71
- * Remove some deprecated endpoints
75
+ - Add Shipment Invoice and Refund Report
76
+ - Remove dependencies on `RestClient` and `MultiJson`
77
+ - Remove some deprecated endpoints
72
78
 
73
79
  ## v3.0.1 (2018-05-17)
74
80
 
75
- * Enforce TLS certificate validity by default
81
+ - Enforce TLS certificate validity by default
76
82
 
77
83
  ## v3.0.0 (2018-02-15)
78
84
 
79
- * Require use of ruby ~> 2.0 and TLSv1.2
85
+ - Require use of ruby ~> 2.0 and TLSv1.2
80
86
 
81
87
  ## v2.7.3 (2018-02-05)
82
88
 
83
- * Fix bug with introduced around certain JSON objects with IDs (thanks vladvinnikov!)
89
+ - Fix bug with introduced around certain JSON objects with IDs (thanks vladvinnikov!)
84
90
 
85
91
  ## v2.7.2 (2018-02-01)
86
92
 
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
93
+ - Removed unused and unsupported code paths for Container model
94
+ - Removed unused and unsupported code path for Stamp and Barcode methods on the Shipment model
95
+ - Fixed a bug with non-model JSON object with an "id" key being treated as models and raising errors
90
96
 
91
97
  ## v2.7.1 (2017-05-25)
92
98
 
93
- * Allow reports to be retrieved without passing a type
99
+ - Allow reports to be retrieved without passing a type
94
100
 
95
101
  ## v2.7.0 (2017-04-04)
96
102
 
97
- * Changed Report CRUD signatures. requires report type to be passed
103
+ - Changed Report CRUD signatures. requires report type to be passed
98
104
 
99
105
  ## v2.6.2 (2017-02-14)
100
106
 
101
- * Added get_rates method for Orders
107
+ - Added get_rates method for Orders
102
108
 
103
109
  ## v2.6.1 (2017-01-19)
104
110
 
105
- * Updated create method for ScanForms
111
+ - Updated create method for ScanForms
106
112
 
107
113
  ## v2.6.0 (2017-01-17)
108
114
 
109
- * Add basic CRUD methods for Webhooks
115
+ - Add basic CRUD methods for Webhooks
110
116
 
111
117
  ## v2.5.0 (2016-12-19)
112
118
 
113
- * Add prefixes to report in utils
119
+ - Add prefixes to report in utils
114
120
 
115
121
  ## v2.4.0 (2016-12-08)
116
122
 
117
- * Add report resource to ruby client
123
+ - Add report resource to ruby client
118
124
 
119
125
  ## v2.3.0 (2016-11-25)
120
126
 
121
- * Updated dependencies to allow rest-client 2.0.0 and above
127
+ - Updated dependencies to allow rest-client 2.0.0 and above
122
128
 
123
129
  ## v2.2.0 (2016-07-260
124
130
 
125
- * Added standalone Insurance model
131
+ - Added standalone Insurance model
126
132
 
127
133
  ## v2.1.11 (2016-02-04)
128
134
 
129
- * Allowed user creation for top-level users
135
+ - Allowed user creation for top-level users
130
136
 
131
137
  ## v2.1.10 (2015-12-23)
132
138
 
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.
139
+ - Added verify and verify_strict params to Address.create
140
+ - Added Tracker.create_list and Tracker.all_updated for working with large
141
+ numbers of Trackers.
136
142
 
137
143
  ## v2.1.9 (2015-11-04)
138
144
 
139
- * Added new tests for Tracker.all
140
- * Updated some old examples
145
+ - Added new tests for Tracker.all
146
+ - Updated some old examples
141
147
 
142
148
  ## v2.1.8 (2015-10-21)
143
149
 
144
- * Added Cancel method for Pickups (thanks Ramie Blatt!)
150
+ - Added Cancel method for Pickups (thanks Ramie Blatt!)
145
151
 
146
152
  ## v2.1.7 (2015-10-05)
147
153
 
148
- * Fixed Address.create_and_verify and changed how errors are raised (thanks Dimitri Roche!)
149
- * Require newer version of the multi_json package
154
+ - Fixed Address.create_and_verify and changed how errors are raised (thanks Dimitri Roche!)
155
+ - Require newer version of the multi_json package
150
156
 
151
157
  ## v2.1.6 (2015-06-10)
152
158
 
153
- * Added Address message accessor for backwards compatability
159
+ - Added Address message accessor for backwards compatability
154
160
 
155
161
  ## v2.1.5 (2015-06-10)
156
162
 
157
- * Removed Address.message
163
+ - Removed Address.message
158
164
 
159
165
  ## v2.1.4 (2015-06-03)
160
166
 
161
- * Add Printer and PrintJob resources.
167
+ - Add Printer and PrintJob resources.
162
168
 
163
169
  ## v2.1.3 (2015-04-30)
164
170
 
165
- * Bux fix, EasyPost::Errors no longer break with a nil json body.
171
+ - Bux fix, EasyPost::Errors no longer break with a nil json body.
166
172
 
167
173
  ## v2.1.2 (2015-04-29)
168
174
 
169
- * EasyPost::Errors now correctly parse field errors and error codes.
175
+ - EasyPost::Errors now correctly parse field errors and error codes.
170
176
 
171
177
  ## v2.1.1 (2015-04-15)
172
178
 
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)
179
+ - CarrierAccount will now correctly save in-place modifications to credentials
180
+ - Nested variables should now be saved correctly across all models
181
+ - Fixed version numbering confusion (the previous version was 2.0.15, not 2.1.0)
176
182
 
177
183
  ## v2.0.15 (2015-04-15)
178
184
 
179
- * Added tracker to shipment buy response
180
- * Updated tracker tests
185
+ - Added tracker to shipment buy response
186
+ - Updated tracker tests
181
187
 
182
188
  ## v2.0.14 (2015-04-15)
183
189
 
184
- * Added User and CarrierAccount models with CRUD functionality
190
+ - Added User and CarrierAccount models with CRUD functionality
185
191
 
186
192
  ## v2.0.13 (2014-10-30)
187
193
 
188
- * Added Pickup, PickupRate resources.
189
- * Added ability to pass api_key to a few resources that were missing it.
194
+ - Added Pickup, PickupRate resources.
195
+ - Added ability to pass api_key to a few resources that were missing it.
190
196
 
191
197
  ## v2.0.12 (2014-07-07)
192
198
 
193
- * Added Item, Container, and Order resources.
194
- * Fixed and added a lot of tests.
199
+ - Added Item, Container, and Order resources.
200
+ - Fixed and added a lot of tests.
195
201
 
196
202
  ## v2.0.11 (2013-12-16)
197
203
 
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
204
+ - Added Event.receive method for parsing events sent by webhook.
205
+ - Fixed tests to account for the tracking code returning and array of details instead of a Hash
200
206
 
201
207
  ## v2.0.10 (2013-10-03)
202
208
 
203
- * API Addition: Event resource added for webhook consumption.
209
+ - API Addition: Event resource added for webhook consumption.
204
210
 
205
211
  ## v2.0.9 (2013-09-19)
206
212
 
207
- * Interface Change: Changed batch.scan_form to batch.create_scan_form to support the ability to refer to scan forms associated to batches.
213
+ - Interface Change: Changed batch.scan_form to batch.create_scan_form to support the ability to refer to scan forms associated to batches.
208
214
 
209
215
  ## v2.0.3 (2013-07-31)
210
216
 
211
- * API Addition: Tracker resource added. Trackers can be used to register any tracking code with EasyPost webhooks.
217
+ - API Addition: Tracker resource added. Trackers can be used to register any tracking code with EasyPost webhooks.
212
218
 
213
219
  ## v2.0.2 (2013-07-23)
214
220
 
215
- * API Addition: Shipment.track_with_code returns tracking details for any tracking code.
221
+ - API Addition: Shipment.track_with_code returns tracking details for any tracking code.
216
222
 
217
223
  ## v2.0.1 (2013-07-07)
218
224
 
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').
225
+ - API Addition: Address.create_and_verify returns a verified address in one step.
226
+ - API Addition: Shipment.label forces the creation of additional label formats (pdf, epl2, zpl).
227
+ - API Addition: Shipment.insure purchases insurance for a shipment.
228
+ - Library Update: Added the ability to negatively filter carriers and services with Shipment.lowest_rate (e.g. '!usps').
223
229
 
224
230
  ## v2.0.0 (2013-06-25)
225
231
 
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.0
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ EasyPost::Connection = Struct.new(:uri, :config, keyword_init: true) do
4
+ attr_reader :connection
5
+
6
+ def initialize(uri:, config:)
7
+ super
8
+
9
+ @connection =
10
+ if config[:proxy]
11
+ proxy_uri = URI(config[:proxy])
12
+ Net::HTTP.new(
13
+ uri.host,
14
+ uri.port,
15
+ proxy_uri.host,
16
+ proxy_uri.port,
17
+ proxy_uri.user,
18
+ proxy_uri.password,
19
+ )
20
+ else
21
+ Net::HTTP.new(uri.host, uri.port)
22
+ end
23
+
24
+ connection.use_ssl = true
25
+
26
+ config.each do |name, value|
27
+ # Discrepancies between RestClient and Net::HTTP.
28
+ case name
29
+ when :verify_ssl
30
+ name = :verify_mode
31
+ when :timeout
32
+ name = :read_timeout
33
+ end
34
+
35
+ # Handled in the creation of the client.
36
+ if name == :proxy
37
+ next
38
+ end
39
+
40
+ connection.public_send("#{name}=", value)
41
+ end
42
+ end
43
+
44
+ # Make an HTTP request with Ruby's {Net::HTTP}
45
+ #
46
+ # @param method [Symbol] the HTTP Verb (get, method, put, post, etc.)
47
+ # @param path [String] URI path of the resource
48
+ # @param requested_api_key [String] ({EasyPost.api_key}) key set Authorization header.
49
+ # @param body [String] (nil) body of the request
50
+ # @raise [EasyPost::Error] if the response has a non-2xx status code
51
+ # @return [Hash] JSON object parsed from the response body
52
+ def call(method, path, api_key = nil, body = nil)
53
+ request = Net::HTTP.const_get(method.capitalize).new(path)
54
+ request.body = JSON.dump(EasyPost::Util.objects_to_ids(body)) if body
55
+
56
+ EasyPost.default_headers.each_pair { |h, v| request[h] = v }
57
+ request['Authorization'] = EasyPost.authorization(api_key) if api_key
58
+
59
+ response = connection.request(request)
60
+
61
+ EasyPost.parse_response(
62
+ status: response.code.to_i,
63
+ body: response.body,
64
+ json: response['Content-Type'].start_with?('application/json'),
65
+ )
66
+ end
67
+ 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.0
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-09 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