Module: BinCheckerRb

Defined in:
lib/bin_checker_rb.rb,
lib/bin_checker_rb/version.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =
"0.2.1"

Class Method Summary collapse

Class Method Details

.check(bin_number, timeout = 5) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bin_checker_rb.rb', line 17

def self.check(bin_number, timeout=5)
  promptapi_endpoint = ENV['PROMPTAPI_TEST_ENDPOINT'] || "https://api.promptapi.com/bincheck/#{bin_number}"
  apikey = ENV['PROMPTAPI_TOKEN'] || nil
  return {error: "You need to set PROMPTAPI_TOKEN environment variable"} unless apikey
  
  conn = Faraday.new(url: promptapi_endpoint, request: {timeout: timeout}) do |c|
    c.use Faraday::Response::RaiseError
  end

  begin
    resp = conn.send(:get) do |req|
      req.headers['Content-Type'] = 'application/json'
      req.headers['apikey'] = apikey
    end
  rescue Faraday::ConnectionFailed
    return {error: "Connection error"}
  rescue Faraday::TimeoutError => e
    return {error: e.message.capitalize}
  rescue Faraday::ClientError => e
    return ::BinCheckerRb.parse(e.response[:body])
  rescue Faraday::ServerError => e
    return {error: e.message.capitalize}
  end
  ::BinCheckerRb.parse(resp.body)
end

.parse(body) ⇒ Object



8
9
10
11
12
13
14
15
# File 'lib/bin_checker_rb.rb', line 8

def self.parse(body)
  begin
    response = JSON.parse(body, symbolize_names: true)
  rescue JSON::ParserError
    return {error: "JSON decoding error"}
  end
  response
end