module Eco module API class MicroCases # Helper to load `People` that works in different phases: # 1. first tries to get the newest cached file that follows `filename` pattern # - if not the newest, it tries to find the specific filename # 2. if it succeeds to identif a cached file, it loads it # - if it fails, it tries to get people from the server # @note # - `filename` will be relative to the working directory (the one of the session `enviro` set by the user). # @param filename [String] the name of the file where the cached data is to be found. # @param modifier [Array] modifiers to specify how this function should proceed: # - `:newest` if it should try to find the newest file (pattern alike). # - `:api` if it should try to get people from the server in case there's no cache. # - `:file` if it is supposed to load people from a file. # - `:save` if it is supposed to cache/save the data locally once obtained people from the server (`:api`) # @return [Eco::API::Organization::People] the `People` object with the data. def people_load(filename = enviro.config.people.cache, modifier: [:newest, :api]) modifier = [modifier].flatten load_file = [:file, :newest].any? {|flag| modifier.include?(flag)} case when filename && load_file if file = people_load_filename(filename, newest: modifier.include?(:newest)) file_manager.load_json(file).tap do |people| logger.info("#{people&.length} people loaded from file #{file}") if people.is_a?(Array) end else logger.error("could not find the file #{file_manager.dir.file(filename)}") exit unless modifier.include?(:api) people_load(modifier: modifier - [:newest, :file]) end when modifier.include?(:api) logger.info("Going to get all the people via API (load)") start = Time.now session.batch.get_people.tap do |people| secs = (Time.now - start).round(3) cnt = people.count per_sec = (cnt.to_f / secs).round(2) logger.info("Loaded #{cnt} people in #{secs} seconds (#{per_sec} people/sec)") if modifier.include?(:save) && people && people.length > 0 file = file_manager.save_json(people, filename, :timestamp) logger.info("#{people.length } people saved to file #{file}.") end end end.yield_self do |people| Eco::API::Organization::People.new(people) end end private def people_load_filename(filename, newest: false) if newest # search input file based on pattern (in case the name has a timestamp) file_manager.dir.newest_file(file: filename).tap do |file| logger.info("previous file found: #{file}") if file end else file_manager.dir.file(filename, should_exist: true) end end end end end