Sha256: 25eabfd81e662900c08689f402cd4babc21f0e42ae8e7e0502268ccdb5fe822b

Contents?: true

Size: 1.56 KB

Versions: 2

Compression:

Stored size: 1.56 KB

Contents

module Lifen
  class Client

    def request(mode, url, params = {})
      before_request

      response = faraday_client.send(mode) do |req|
        req.url url

        req.headers['Authorization']      = "Bearer #{bearer}"
        req.headers['Content-Type']       = "application/json"
        req.headers['Accept']             = "application/json"

        req.body = JSON.generate(params)
      end

      handle_status!(response)

      json = JSON.parse response.body

      json
    end

    def post(url, params = {})
      request(:post, url, params)
    end

    def get(url, params = {})
      request(:get, url, params)
    end

    private

      def handle_status!(response)
        if response.status == 500
          json = JSON.parse response.body

          trace_id = json.fetch("X-B3-TraceId", "unknown")
          raise Error, "Error 500, Internal server error (trace ID: #{trace_id})"
        end
      end

      def faraday_client
        @faraday_client ||= Faraday.new(faraday_options) do |faraday|
          faraday.request  :url_encoded             # form-encode POST params
          faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
        end
      end

      def faraday_options
        options = {url: site}

        options[:proxy] = proxy_url if !proxy_url.nil?

        options
      end

      def site
        Lifen.configuration.site
      end

      def proxy_url
        Lifen.configuration.proxy_url
      end

      def before_request
      end

      def bearer
        raise "A bearer method must be defined"
      end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
lifen-1.0.1 lib/lifen/client.rb
lifen-1.0.0 lib/lifen/client.rb