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" } body_data(response.body).each.with_index do |subresponse, idx| byebug status = subresponse["status"] method = @operations[idx][:method] body = subresponse["response"] callback = @operations[idx][:callback] if status == 200 && method == "GET" batch_response = BatchResponse.new(status, body, @wrapper.new(body)) log_batch_response(@operations[idx], batch_response) callback&.call(batch_response, batch_response.result) else batch_response = BatchResponse.new(status, body) log_batch_response(@operations[idx], batch_response) callback&.call(batch_response) end end end def get(doc, &block) id = get_id(doc) @operations << { path: "#{@base_path}/#{CGI.escape(id)}", method: "GET", callback: block } end def update(doc, &block) id = get_id(doc) body = get_body(doc) @operations << { path: "#{@base_path}/#{CGI.escape(id)}", method: "PATCH", body: body, callback: block } end def upsert(doc, &block) id = get_id(doc) body = get_body(doc) @operations << { path: "#{@base_path}/#{CGI.escape(id)}", method: "POST", body: body, callback: block } end def delete(doc, &block) id = get_id(doc) @operations << { path: "#{@base_path}/#{CGI.escape(id)}", method: "DELETE", callback: block } end def create(doc, &block) body = get_body(doc) @operations << { path: @base_path, method: "POST", body: body, callback: block } end private # Hook for other api versions to obtain the raw data of a response # @note this was introduced to allow `v2` to reuse this class def body_data(body) body end def log_batch_response(operation, response) log(:info) { "BATCH #{operation[:method]} #{operation[:path]}" } log(:info) { "Status #{response.status}" } level = response.success?? :debug : :warn log(level) { "Response: #{JSON.pretty_generate(response.body)}" } end def log(level, &block) @logger&.send(level, &block) end end end end end