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