lib/ecoportal/api/common/batch_operation.rb in ecoportal-api-0.3.4 vs lib/ecoportal/api/common/batch_operation.rb in ecoportal-api-0.3.5

- old
+ new

@@ -3,14 +3,15 @@ module API module Common class BatchOperation include Common::DocHelpers - def initialize(base_path, wrapper) + def initialize(base_path, wrapper, logger: nil) @base_path = base_path @wrapper = wrapper @operations = [] + @logger = logger end def as_json { actions: @operations.map do |operation| @@ -18,25 +19,31 @@ end } end def process_response(response) - raise "Total failure in batch operation" unless response.success? + unless response.success? + log(:error) { "Total failure in batch operation." } + raise "Total failure in batch operation" + end + log(:info) { "Processing batch responses" } + response.body.each.with_index do |subresponse, idx| - next unless callback = @operations[idx][:callback] + callback = @operations[idx][:callback] + status = subresponse["status"] + body = subresponse["response"] + method = @operations[idx][:method] - status = subresponse["status"] - body = subresponse["response"] - method = @operations[idx][:method] - if status == 200 && method == "GET" batch_response = BatchResponse.new(status, body, @wrapper.new(body)) - callback.call batch_response, batch_response.result + log_batch_response(@operations[idx], batch_response) + callback && callback.call(batch_response, batch_response.result) else batch_response = BatchResponse.new(status, body) - callback.call batch_response + log_batch_response(@operations[idx], batch_response) + callback && callback.call(batch_response) end end end def get(doc) @@ -85,9 +92,22 @@ path: @base_path, method: "POST", body: body, callback: block_given? && Proc.new } + end + + private + + def log_batch_response(operation, response) + level = response.success?? :debug : :warn + log(:info) { "BATCH #{operation[:method]} #{operation[:path]}" } + log(:info) { "Status #{response.status}" } + log(level) { "Response: #{JSON.pretty_generate(response.body)}" } + end + + def log(level, &block) + @logger.send(level, &block) if @logger end end end end end