Sha256: ca9e30d85b004c520f7a0b05b1b41912e7687c3782dc0fdd0d8cd209e264cd84

Contents?: true

Size: 1.57 KB

Versions: 18

Compression:

Stored size: 1.57 KB

Contents

module Wovnrb
  class ApiData
    def initialize(access_url, store)
      @access_url = access_url.gsub(/\/$/, '')
      @store = store
    end

    def get_data
      cache_key = to_key(@access_url)
      data = get_data_value(cache_key)
      JSON.parse(data)
    end

    private
    def get_data_value(cache_key)
      cache_value = CacheBase.get_single.get(cache_key)
      return cache_value if cache_value

      uri = build_api_uri
      begin
        response = get_from_api_server(uri)
      rescue => e
        response = '{}'
        WovnLogger.instance.error("API server GET request failed :\nurl: #{uri}\n#{e.message}")
      end

      # Always cache response, even when error returns to avoid DDOS
      CacheBase.get_single.put(cache_key, response)
      response
    end

    @@cache_prefix = 'api::cache::'
    def to_key(url)
      "::" + @store.settings['project_token'] + "::#{@@cache_prefix}#{url}"
    end

    def build_api_uri
      t = CGI::escape(@store.settings['project_token'])
      u = CGI::escape(@access_url)
      URI.parse("#{@store.settings['api_url']}?token=#{t}&url=#{u}")
    end

    def get_from_api_server(uri)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = true if uri.scheme == 'https'
      http.open_timeout = @store.settings['api_timeout_seconds']
      http.read_timeout= @store.settings['api_timeout_seconds']
      response = http.start {
        http.get(uri.request_uri)
      }

      if response.code == '200'
        response.body
      else
        raise "Response Code is not success: #{response.code}"
      end
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
wovnrb-1.1.0 lib/wovnrb/api_data.rb
wovnrb-1.0.13 lib/wovnrb/api_data.rb
wovnrb-1.0.12 lib/wovnrb/api_data.rb
wovnrb-1.0.11 lib/wovnrb/api_data.rb
wovnrb-1.0.10 lib/wovnrb/api_data.rb
wovnrb-1.0.9 lib/wovnrb/api_data.rb
wovnrb-1.0.8 lib/wovnrb/api_data.rb
wovnrb-1.0.7 lib/wovnrb/api_data.rb
wovnrb-1.0.6 lib/wovnrb/api_data.rb
wovnrb-1.0.5 lib/wovnrb/api_data.rb
wovnrb-1.0.4 lib/wovnrb/api_data.rb
wovnrb-1.0.2 lib/wovnrb/api_data.rb
wovnrb-1.0.1 lib/wovnrb/api_data.rb
wovnrb-1.0.0 lib/wovnrb/api_data.rb
wovnrb-0.2.30 lib/wovnrb/api_data.rb
wovnrb-0.2.29 lib/wovnrb/api_data.rb
wovnrb-0.2.28 lib/wovnrb/api_data.rb
wovnrb-0.2.27 lib/wovnrb/api_data.rb