Class: OASRequest::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/oas_request/http.rb

Class Method Summary collapse

Class Method Details

.config(opts = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/oas_request/http.rb', line 14

def self.config(opts = {})
  # set default options
  opts[:host] ||= "localhost"
  opts[:path] ||= "/"
  opts[:port] ||= 443
  opts[:protocol] ||= "https"
  opts[:headers] ||= {}

  # set standard header values
  opts[:headers]["accept"] = "application/json"

  if opts[:body]
    # set content-type header when body is present
    opts[:headers]["content-type"] = "application/json"

    # ensure body is in JSON format
    opts[:body] = opts[:body].to_json
  end

  opts
end

.get_request(method, opts = {}) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/oas_request/http.rb', line 36

def self.get_request(method, opts = {})
  raise "Unknown method #{method}" unless REQUEST_CLASSES.has_key? method.downcase.to_sym

  uri = URI "#{opts[:protocol]}://#{opts[:host]}:#{opts[:port]}#{opts[:path]}"

  request_class = REQUEST_CLASSES[method.downcase.to_sym]

  req = request_class.new uri, opts[:headers]

  req.body = opts[:body] if opts[:body]

  req
end

.http(headers:, host:, method:, port:, body:, path:, protocol:) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/oas_request/http.rb', line 50

def self.http(headers:, host:, method:, port:, body:, path:, protocol:)
  options = config(
    host: host,
    path: path,
    port: port,
    protocol: protocol,
    headers: headers,
    body: body
  )

  req = get_request method, options

  http = Net::HTTP.new options[:host], options[:port]
  http.use_ssl = options[:protocol] == "https"

  response = http.request req

  headers = response.to_hash
  body = response.body
  if headers.fetch("content-type", []).join.include? "application/json"
    begin
      body = JSON.parse response.body
    rescue
      body = response.body
    end
  end

  {
    headers: headers,
    status_code: response.code.to_i,
    status_message: response.message,
    body: body
  }
end