Sha256: 849c945fdaf63923b98b2d0cacfb46cb5e868dd4584de62c77cb6c2489ca8ff0

Contents?: true

Size: 1.5 KB

Versions: 3

Compression:

Stored size: 1.5 KB

Contents

module Superfaktura
  class BaseApi
    SUPERFAKTURA_URL = 'https://moja.superfaktura.sk'.freeze

    def self.client
      Faraday.new(url: SUPERFAKTURA_URL) do |builder|
        builder.request :url_encoded
        builder.request :json
        builder.response :json

        builder.adapter Faraday.default_adapter
      end
    end

    def self.file_client
      Faraday.new(url: SUPERFAKTURA_URL) do |builder|
        builder.request :url_encoded
        builder.request :json

        builder.adapter Faraday.default_adapter
      end
    end

    def self.request(uri, method = 'POST', payload = nil)
      response = client.public_send(method.downcase.to_sym) do |request|
        request.headers['Authorization'] = "SFAPI email=#{Superfaktura.config.email}&apikey=#{Superfaktura.config.token}"

        request.url(uri)
        request.body = "data=#{payload.to_json}" if payload
      end
      raise Superfaktura::Error, response.body['error_message'] unless response.body['error'].zero?

      response.body
    end

    def self.post(path, payload)
      request(path, 'POST', payload)
    end

    def self.get(path, payload = nil)
      request(path, 'GET', payload)
    end

    def self.file(uri)
      response = file_client.get(uri) do |request|
        request.headers['Authorization'] = "SFAPI email=#{Superfaktura.config.email}&apikey=#{Superfaktura.config.token}"
      end
      raise Superfaktura::Error, response.body['error_message'] unless response.status == 200

      response.body
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
superfaktura-0.9.5 lib/superfaktura/base_api.rb
superfaktura-0.9.4 lib/superfaktura/base_api.rb
superfaktura-0.9.3 lib/superfaktura/base_api.rb