Sha256: b34c2a8506ab23eb7cb2988094ad0b0cb466eddf2cf7e7aee00a675fb598acc0

Contents?: true

Size: 1.88 KB

Versions: 2

Compression:

Stored size: 1.88 KB

Contents

require 'httparty'
require 'wing/actions'
require 'wing/error'

module Wing
  class Client
    include Wing::Actions::Stores
    include Wing::Actions::Orders

    API_VERSION = "v1".freeze
    BASE_URL = "https://api.wing.eu/".freeze
    USER_AGENT = "wing-ruby/#{VERSION}".freeze

    def initialize(api_key: nil, api_secret: nil)
      @api_key = api_key || Wing::configuration.api_key
      @api_secret = api_secret || Wing::configuration.api_secret
    end

    def base_url
      "#{BASE_URL}#{API_VERSION}"
    end

    def get(path, options = {})
      execute(:get, path, options)
    end

    def post(path, data = {}, options = {})
      execute(:post, path, options.merge(body: data))
    end

    private

    attr_reader :api_key, :api_secret

    def execute(method, path, options)
      begin
        response = request(method, path, options)
      rescue *Error::NET_HTTP_ERRORS => err
        raise ConnectionError.new, err.message
      end

      case response.code
      when 200..299
        response
      when 400
        raise BadRequestError.new(response['errorDescription'])
      when 401
        raise AuthenticationError.new(response['errorDescription'])
      when 404
        raise NotFoundError.new(response['errorDescription'])
      when 400..499
        raise ResponseError.new(response['errorDescription'])
      when 500
        raise InternalServerError.new(response['errorDescription'])
      when 500..599
        raise ServerError.new(response['errorDescription'])
      end
    end

    def request(method, path, options)
      HTTParty.send(method, base_url + path, base_options.merge(options))
    end

    def base_options
      {
        format: :json,
        headers: {
          "Accept" => "application/json",
          "User-Agent" => USER_AGENT
        },
        basic_auth: {
          username: api_key,
          password: api_secret
        }
      }
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
wing.rb-0.1.2 lib/wing/client.rb
wing.rb-0.1.1 lib/wing/client.rb