module Eco module API class Session class Batch class Status < Common::Session::BaseSession @types = [:exact, :search] attr_reader :source_queue attr_reader :queue, :method, :type attr_reader :root class << self attr_reader :types def valid_type?(value) types.include?(value) end end def initialize(e, queue:, method:, type: :exact) super(e) fatal("In batch operations you must batch an Enumerable. Received: #{queue}") unless queue && queue.is_a?(Enumerable) self.type = type @method = method @source_queue = queue que = queue.to_a que = queue if queue.respond_to?(:uniq) if que.length != que.uniq.length logger.warn("Please, review your entries-to-query builder, you have repeated entries") queue = que.uniq end @queue = queue @hash = @queue.each_with_index.map do |entry, i| [entry, i] end.to_h @responses = [] @person_match = [] @people_match = Array.new(@queue.length, []) end def root=(object) @root = object end def type=(value) fatal("Invalid :type '#{value}. You must specify type: as one of #{self.class.types} ") unless self.class.valid_type?(value) @type = value end def errors @errors ||= Batch::Errors.new(status: self) end def [](key) @responses[to_index(key)] end def []=(key, response) @responses[to_index(key)] = response end def person(key) return self[key].result if success?(key) nil end def person_match(key) @person_match[to_index(key)] end def set_person_match(key, person) @person_match[to_index(key)] = person end def people_match(key) @people_match[to_index(key)] end def set_people_match(key, people) @people_match[to_index(key)] = people end def received?(key) !!self[key] end def success?(key) self[key]&.success? end def people fatal "This batch wasn't a 'get'. Can't obtain people without 'get' method" unless method == :get #out = Eco::API::Organization::People.new([]) if type == :exact out = Array(queue.length) @responses.each_with_index do |response, i| # out = out.merge([response.result]) if respose.success? out[i] = response.result if response.success? end elsif type == :search out = [] queue.each_with_index.map do |entry, i| pers = person(entry) pers ||= person_match(entry) ppl = pers ? [pers] : people_match(entry) out += ppl # out = out.merge(ppl) unless ppl.empty? end end out end def to_index(key) key.is_a?(Integer) ? valid_index(index: key) : valid_index(entry: key) end def valid_index(index: nil, entry: nil) index ||= @hash[entry] unless index && index < @queue.length fatal "You must provide either the index or the original entry object of the batch" end index end end end end end end