Sha256: 76b90ac5e032fa1498ef4d9ffa39fdd8fd42d1731f138711e65e667262c4d940

Contents?: true

Size: 1.95 KB

Versions: 9

Compression:

Stored size: 1.95 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_errors(response, params)

      json = JSON.parse response.body

      json
    end

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

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

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

    private

      def handle_errors(response, params)
        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}), #{response_error(response, params)}"
        end
      end

      def faraday_client
        @faraday_client ||= Faraday.new(faraday_options) do |faraday|
          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 response_error(response, params)
        "#{response.env.method.upcase} '#{response.env.url}' with params '#{params.inspect}' and bearer '#{trucanted_bearer}'"
      end

      def trucanted_bearer
        if m = /^(.{24})(.*)$/.match(bearer)
          "#{m[1]}#{"*" * m[2].length}"
        else
          bearer
        end
      end

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

  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
lifen-1.6.3 lib/lifen/client.rb
lifen-1.6.2 lib/lifen/client.rb
lifen-1.6.1 lib/lifen/client.rb
lifen-1.6.0 lib/lifen/client.rb
lifen-1.5.2 lib/lifen/client.rb
lifen-1.5.1 lib/lifen/client.rb
lifen-1.5.0 lib/lifen/client.rb
lifen-1.4.0 lib/lifen/client.rb
lifen-1.3.0 lib/lifen/client.rb