Class: Bckbn::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/bckbn/connection.rb

Defined Under Namespace

Classes: BaseHttpError

Constant Summary collapse

HttpBadRequest =
Class.new(BaseHttpError)
HttpInternalServerError =
Class.new(BaseHttpError)
HttpServiceUnavailable =
Class.new(BaseHttpError)
HttpGatewayTimeout =
Class.new(BaseHttpError)
ERRORS =
{
  Net::HTTPBadRequest => HttpBadRequest, # 400
  Net::HTTPInternalServerError => HttpInternalServerError, # 500
  Net::HTTPServiceUnavailable => HttpServiceUnavailable, # 503
  Net::HTTPGatewayTimeout => HttpGatewayTimeout # 504
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(per_req_config) ⇒ Connection

Returns a new instance of Connection.



28
29
30
31
32
33
34
# File 'lib/bckbn/connection.rb', line 28

def initialize(per_req_config)
  global_config = Bckbn.config.to_h
  config = global_config.merge(per_req_config)

  @config = Bckbn::Configuration.new(**config)
  @logs = []
end

Instance Method Details

#get_from_api(path, klass) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/bckbn/connection.rb', line 62

def get_from_api(path, klass)
  log(:debug, "GET #{path}\n")

  url = URI.parse(config.api_base + path)
  request = Net::HTTP::Get.new(url.path)
  bckbn_headers = headers(config)
  bckbn_headers.reject! { |_, v| v.nil? || v == "" }
  bckbn_headers.each { |k, v| request[k] = v }

  response_handler(url, request) do |response, rbody|
    case response
    when Net::HTTPSuccess
      data = rbody.fetch("data")
      log(:debug, "\nResponse: #{data.to_json}")
      klass.new(**data, logs: @logs)
    else
      err_klass = ERRORS.fetch(response.class)
      message = "Error: #{rbody ? rbody["errors"] : "Unknown"}"
      log(:error, message)

      err = err_klass.new(message, @logs)
      raise err
    end
  end
end

#post_to_api(path, body, klass) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/bckbn/connection.rb', line 36

def post_to_api(path, body, klass)
  log(:debug, "POST #{path}\n\nData: #{body.to_json}")

  url = URI.parse(config.api_base + path)
  request = Net::HTTP::Post.new(url.path)
  bckbn_headers = headers(config)
  bckbn_headers.reject! { |_, v| v.nil? || v == "" }
  bckbn_headers.each { |k, v| request[k] = v }
  request.body = body.to_json

  response_handler(url, request) do |response, rbody|
    case response
    when Net::HTTPSuccess
      data = rbody.fetch("data")
      log(:debug, "\nResponse: #{data.to_json}")
      klass.new(**data, logs: @logs)
    else
      err_klass = ERRORS.fetch(response.class)
      message = "Error: #{rbody ? rbody["errors"] : "Unknown"}"
      log(:error, message)
      err = err_klass.new(message, @logs)
      raise err
    end
  end
end