module Ecoportal module API module Common class BatchOperation include Common::DocHelpers 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| operation.slice(:path, :method, :body) end } end def process_response(response) 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| callback = @operations[idx][:callback] status = subresponse["status"] body = subresponse["response"] method = @operations[idx][:method] if status == 200 && method == "GET" batch_response = BatchResponse.new(status, body, @wrapper.new(body)) log_batch_response(@operations[idx], batch_response) callback && callback.call(batch_response, batch_response.result) else batch_response = BatchResponse.new(status, body) log_batch_response(@operations[idx], batch_response) callback && callback.call(batch_response) end end end def get(doc) id = get_id(doc) @operations << { path: @base_path + "/" + CGI::escape(id), method: "GET", callback: block_given? && Proc.new } end def update(doc) id = get_id(doc) body = get_body(doc) @operations << { path: @base_path + "/" + CGI::escape(id), method: "PATCH", body: body, callback: block_given? && Proc.new } end def upsert(doc) id = get_id(doc) body = get_body(doc) @operations << { path: @base_path + "/" + CGI::escape(id), method: "POST", body: body, callback: block_given? && Proc.new } end def delete(doc) id = get_id(doc) @operations << { path: @base_path + "/" + CGI::escape(id), method: "DELETE", callback: block_given? && Proc.new } end def create(doc) body = get_body(doc) @operations << { 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