Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle HTTPX:ErrorResponses and add Logging #24

Merged
merged 1 commit into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions lib/zatca/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,14 @@ class ZATCA::Client
DEFAULT_API_VERSION = "V2".freeze
LANGUAGES = %w[ar en].freeze

def initialize(username:, password:, language: "ar", version: DEFAULT_API_VERSION, environment: :production)
def initialize(username:, password:, language: "ar", version: DEFAULT_API_VERSION, environment: :production, verbose: false)
raise "Invalid language: #{language}, Please use one of: #{LANGUAGES}" unless LANGUAGES.include?(language)

@username = username
@password = password
@language = language
@version = version
@verbose = verbose

@base_url = ENVIRONMENTS_TO_URLS_MAP[environment.to_sym] || PRODUCTION_BASE_URL
end
Expand Down Expand Up @@ -132,21 +133,37 @@ def request(method:, path:, body: {}, headers: {}, authenticated: true)
url = "#{@base_url}/#{path}"
headers = default_headers.merge(headers)

log("Requesting #{method} #{url} with\n\nbody: #{body}\n\nheaders: #{headers}\n")

client = if authenticated
authenticated_request_cilent
else
unauthenticated_request_client
end

response = client.send(method, url, json: body, headers: headers)
log("Raw response: #{response}")

if response.instance_of?(HTTPX::ErrorResponse)
return {
message: response.to_s,
response_headers: response.response&.headers&.to_s,
response_body: response.response&.body&.to_s,
status: response.response&.status
}
end

response_body = response.body.to_s

if response.headers["Content-Type"] == "application/json"
parsed_body = if response.headers["Content-Type"] == "application/json"
parse_json_or_return_string(response_body)
else
response_body
end

log("Response body: #{parsed_body}")

parsed_body
end

def authenticated_request_cilent
Expand All @@ -170,4 +187,11 @@ def parse_json_or_return_string(json)
rescue JSON::ParserError
json
end

def log(message)
return unless @verbose
message = "\n\n---------------------\n\n#{message}\n\n"

puts message
end
end
2 changes: 1 addition & 1 deletion lib/zatca/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module ZATCA
VERSION = "1.0.1"
VERSION = "1.0.2"
end
Loading