From 5c2db0655ae8e4639ea38dfb5c03ea43a25028af Mon Sep 17 00:00:00 2001 From: Omar Bahareth Date: Wed, 20 Dec 2023 17:42:45 +0300 Subject: [PATCH] Handle HTTPX:ErrorResponses and add Logging - Add a new `verbose` option to ZATCA::Client that logs requests and responses when `true`, defaulted to `false`. - When there is an error, parse HTTPX::ErrorResponse into a hash and return it. --- lib/zatca/client.rb | 28 ++++++++++++++++++++++++++-- lib/zatca/version.rb | 2 +- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/zatca/client.rb b/lib/zatca/client.rb index c3c3211..03f9080 100644 --- a/lib/zatca/client.rb +++ b/lib/zatca/client.rb @@ -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 @@ -132,6 +133,8 @@ 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 @@ -139,14 +142,28 @@ def request(method:, path:, body: {}, headers: {}, authenticated: true) 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 @@ -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 diff --git a/lib/zatca/version.rb b/lib/zatca/version.rb index 53a6f9d..0f12650 100644 --- a/lib/zatca/version.rb +++ b/lib/zatca/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module ZATCA - VERSION = "1.0.1" + VERSION = "1.0.2" end