Class: Sibit::Json

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

Overview

JSON processing.

Instance Method Summary collapse

Constructor Details

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

Constructor.



43
44
45
46
# File 'lib/sibit/json.rb', line 43

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

Instance Method Details

#get(uri, 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.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sibit/json.rb', line 51

def get(uri, headers: {}, accept: [200])
  start = Time.now
  res = @http.client(uri).get(
    "#{uri.path.empty? ? '/' : uri.path}#{uri.query ? "?#{uri.query}" : ''}",
    {
      'Accept' => 'application/json',
      'User-Agent' => user_agent,
      'Accept-Charset' => 'UTF-8',
      'Accept-Encoding' => ''
    }.merge(headers)
  )
  unless accept.include?(res.code.to_i)
    raise Sibit::Error, "Failed to retrieve #{uri} (#{res.code}): #{res.body}"
  end
  @log.info("GET #{uri}: #{res.code}/#{res.body.length}b in #{age(start)}")
  JSON.parse(res.body)
end

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



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/sibit/json.rb', line 69

def post(uri, body, headers: {})
  start = Time.now
  res = @http.client(uri).post(
    "#{uri.path}?#{uri.query}",
    "tx=#{CGI.escape(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
  @log.info("POST #{uri}: #{res.code} in #{age(start)}")
end