Sha256: 3d547910775f8887297e8c24772aa6f9e38321be49160aac0e10880e7722442c

Contents?: true

Size: 1.75 KB

Versions: 3

Compression:

Stored size: 1.75 KB

Contents

# frozen_string_literal: true

require "rest-client"
require "json"
require_relative "../response/api_error"
require_relative "../error/api_error"

module ONEAccess
  module API
    class Base
      class << self
        def send_get(method, params = {})
          RestClient.get(api_url(method), { params: params }.merge(auth_headers))
        rescue RestClient::Exception => e
          raise create_api_error(e)
        end

        def send_post(method, body)
          RestClient.post(api_url(method), body.to_json, { content_type: :json }.merge(auth_headers))
        rescue RestClient::Exception => e
          raise create_api_error(e)
        end

        def resource_api_path
          const_get("RESOURCE_API_PATH")
        rescue StandardError
          nil
        end

        def api_url(method = nil)
          url = "#{Configuration.base_url}#{resource_api_path}"
          return url if method.nil?
          "#{url}/#{method}"
        end

        protected

        def api_path(path)
          raise "API path has already been set" if resource_api_path
          self.resource_api_path = path
        end

        private

        def create_api_error(error)
          api_error_data = Response::APIError.new
          Response::Representer::APIError.new(api_error_data).from_json(error.http_body)
          Error::APIError.new(error.http_code, api_error_data.api_status_code, api_error_data.api_status_message)
        end

        def resource_api_path=(path)
          const_set("RESOURCE_API_PATH", path)
        end

        def auth_headers
          {
            "X-One-Access-Api-Key" => Configuration.api_key,
            "Authorization"        => "X-One-Access-Master-Api-Key #{Configuration.master_api_key}"
          }
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
oneaccess-0.1.9 lib/oneaccess/api/base.rb
oneaccess-0.1.8 lib/oneaccess/api/base.rb
oneaccess-0.1.7 lib/oneaccess/api/base.rb