Class: Sibit::Json

Inherits:
Object
  • Object
show all
Defined in:
lib/sibit/json.rb

Overview

Json SDK.

It works through the Blockchain API: https://www.blockchain.com/api/blockchain_api

Author

Yegor Bugayenko (yegor256@gmail.com)

Copyright

Copyright (c) 2019-2026 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(log: Loog::NULL, http: Sibit::Http.new) ⇒ Json

Constructor.



24
25
26
27
# File 'lib/sibit/json.rb', line 24

def initialize(log: Loog::NULL, http: Sibit::Http.new)
  @http = http
  @log = log
end

Instance Method Details

#get(address, headers: {}, accept: [200]) ⇒ Object

Send GET request to the HTTP and return JSON response. This method will also log the process and will validate the response for correctness.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/sibit/json.rb', line 32

def get(address, headers: {}, accept: [200])
  ret = nil
  elapsed(@log) do
    uri = URI(address.to_s)
    res = @http.client(uri).get(
      "#{uri.path.empty? ? '/' : uri.path}#{"?#{uri.query}" if uri.query}",
      {
        'Accept' => 'application/json',
        'User-Agent' => user_agent,
        'Accept-Charset' => 'UTF-8',
        'Accept-Encoding' => ''
      }.merge(headers)
    )
    unless accept.include?(Integer(res.code, 10))
      raise(Sibit::Error, "Failed to retrieve #{uri} (#{res.code}): #{res.body}")
    end
    ret =
      begin
        JSON.parse(res.body)
      rescue JSON::ParserError => e
        raise(Sibit::Error, "Can't parse JSON: #{e.message}")
      end
    throw(:"GET #{uri}: #{res.code}/#{length(res.body.length)}")
  end
  ret
end

#post(address, body, headers: {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/sibit/json.rb', line 59

def post(address, body, headers: {})
  uri = URI(address.to_s)
  elapsed(@log) do
    res = @http.client(uri).post(
      "#{uri.path.empty? ? '/' : uri.path}#{"?#{uri.query}" if uri.query}",
      body,
      {
        'Accept' => 'text/plain',
        'User-Agent' => user_agent,
        'Accept-Charset' => 'UTF-8',
        'Accept-Encoding' => '',
        'Content-Type' => 'application/x-www-form-urlencoded'
      }.merge(headers)
    )
    unless res.code == '200'
      raise(Sibit::Error, "Failed to post tx to #{uri}: #{res.code}\n#{res.body}")
    end
    throw(:"POST #{uri}: #{res.code}")
  end
end