module Ecoportal module API module Common class BatchOperation include Common::DocHelpers def initialize(base_path, wrapper, logger: nil, deep_logging: false) @base_path = base_path @wrapper = wrapper @operations = [] @logger = logger @deep_logging = deep_logging end def count @operations.count end def as_json { actions: @operations.map do |operation| operation.slice(:path, :method, :body) end } end def process_response(response) unless response.success? msg = "Error: total failure in batch operation." log(:debug) { msg } raise msg end log(:debug) { "Processing batch responses" } if deep_logging? body_data(response.body).each.with_index do |subresponse, idx| 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) return unless deep_logging? log(:debug) { "BATCH #{operation[:method]} #{operation[:path]}" } log(:debug) { "Status #{response.status}" } log(:debug) { "Response: #{JSON.pretty_generate(response.body)}" } end def deep_logging? @deep_logging end def log(level, &block) puts "(#{level}) #{yield}" @logger&.send(level, &block) end end end end end