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] batch_response = BatchResponse.new(status, body) if batch_response.success? && method == "GET" callback.call response, @wrapper.new(body) else callback.call batch_response end end else raise "Total failure in batch operation" end end def get(id) @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 end end end end