Class: INatGet::App::Server::API
- Inherits:
-
INatGet::App::Server
- Object
- INatGet::App::Server
- INatGet::App::Server::API
- Defined in:
- lib/inat-get/app/core/api.rb
Instance Attribute Summary
Attributes inherited from INatGet::App::Server
Instance Method Summary collapse
- #faraday ⇒ Object private
- #get(query, **opts) ⇒ Object private
-
#initialize(socket_path, **params) ⇒ API
constructor
A new instance of API.
Methods inherited from INatGet::App::Server
#after_loop, #before_loop, create, #on_error, #process_msg, #run, used?, wait_answer?
Constructor Details
#initialize(socket_path, **params) ⇒ API
Returns a new instance of API.
12 13 14 15 16 17 18 |
# File 'lib/inat-get/app/core/api.rb', line 12 def initialize socket_path, **params @console = params.delete :console @logger = ::INatGet::App::ConsoleLogger::new @console, progname: 'API' super(socket_path, **params) @config = INatGet::App::Setup::config @delay = IS::Duration::parse @config.dig(:api, :delay) end |
Instance Method Details
#faraday ⇒ Object (private)
50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/inat-get/app/core/api.rb', line 50 def faraday # tmp_logger = ::Logger::new 'common.log', level: :info @faraday ||= Faraday::new do |f| f.request :retry, max: @config.dig(:api, :retry, :max), interval: IS::Duration::parse(@config.dig(:api, :retry, :interval)), interval_randomness: @config.dig(:api, :retry, :randomness), backoff_factor: @config.dig(:api, :retry, :backoff), exceptions: [Faraday::TimeoutError, Faraday::ConnectionFailed, Faraday::SSLError, Faraday::ClientError] f.request :url_encoded # f.response :logger, tmp_logger, bodies: true, headers: true f.adapter Faraday::default_adapter end end |
#get(query, **opts) ⇒ Object (private)
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/inat-get/app/core/api.rb', line 22 def get query, **opts endpoint = @config.dig(:api, :root) + query[:endpoint].to_s timepoint = Time::now if @last_request delta = timepoint - @last_request sleep (@delay - delta) if delta < @delay end @last_request = timepoint response = faraday.get(endpoint) do |rq| rq.params[:per_page] = @config.dig(:api, :pager) rq.params.compact! rq.params.merge! query[:query] rq.headers["User-Agent"] = "iNatGet v#{INatGet::Info::VERSION} (#{ INatGet::Info::VERSION_ALIAS })" end if response.success? begin data = JSON.parse response.body, symbolize_names: true return data.freeze rescue => e @logger.error "Error while parsing: #{e.}" return { status: :error, error: e. }.freeze end else @logger.error "Error in response: #{response.status}" return { status: :error, error: response.status }.freeze end end |