require 'ecoportal/api/common/doc_helpers' module Ecoportal module API module Common class BatchOperation include Common::DocHelpers def initialize(base_path, wrapper) @base_path = base_path @wrapper = wrapper @operations = [] end def as_json { actions: @operations.map do |operation| operation.slice(:path, :method, :body) end } end def process_response(response) if response.success? response.body.each.with_index do |subresponse, idx| next unless 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)) callback.call batch_response, batch_response.result else batch_response = BatchResponse.new(status, body) callback.call batch_response end end else raise "Total failure in batch operation" 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) external_id = get_external_id(doc) body = get_body(doc) @operations << { path: @base_path + "/" + CGI::escape(external_id || 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 end end end end