Skip to content

Commit ef3beb8

Browse files
committed
add default http client adapter
1 parent 91a5025 commit ef3beb8

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

lib/optimizely/cmab/cmab_client.rb

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ def initialize(http_client = nil, retry_config = nil, logger = nil)
4949
# http_client: HTTP client for making requests.
5050
# retry_config: Configuration for retry settings.
5151
# logger: Logger for logging errors and info.
52-
@http_client = http_client || Optimizely::Helpers::HttpUtils
52+
@http_client = http_client || DefaultHttpClient.new
5353
@retry_config = retry_config || CmabRetryConfig.new
5454
@logger = logger || NoOpLogger.new
5555
end
@@ -172,4 +172,53 @@ def _do_fetch_with_retry(url, request_body, retry_config, timeout)
172172
raise CmabFetchError, error_message
173173
end
174174
end
175+
176+
class DefaultHttpClient
177+
# Default HTTP client for making requests.
178+
# Uses Optimizely::Helpers::HttpUtils to make requests.
179+
180+
def post(url, json: nil, headers: {}, timeout: nil)
181+
# Makes a POST request to the specified URL with JSON body and headers.
182+
# Args:
183+
# url: The endpoint URL.
184+
# json: The JSON payload to send in the request body.
185+
# headers: Additional headers for the request.
186+
# timeout: Maximum wait time for the request to respond in seconds.
187+
# Returns:
188+
# The response object.
189+
190+
response = Optimizely::Helpers::HttpUtils.make_request(url, :post, json.to_json, headers, timeout)
191+
192+
HttpResponseAdapter.new(response)
193+
end
194+
195+
class HttpResponseAdapter
196+
# Adapter for HTTP response to provide a consistent interface.
197+
# Args:
198+
# response: The raw HTTP response object.
199+
200+
def initialize(response)
201+
@response = response
202+
end
203+
204+
def status_code
205+
@response.code.to_i
206+
end
207+
208+
def json
209+
JSON.parse(@response.body)
210+
rescue JSON::ParserError
211+
raise Optimizely::CmabInvalidResponseError, 'Invalid JSON response from CMAB service.'
212+
end
213+
214+
def body
215+
@response.body
216+
end
217+
end
218+
end
219+
220+
class NoOpLogger
221+
# A no-operation logger that does nothing.
222+
def log(_level, _message); end
223+
end
175224
end

0 commit comments

Comments
 (0)