Class: ReeHttp::BuildRequest

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_http/package/ree_http/functions/build_request.rb

Constant Summary collapse

DEFAULT_PROTOCOL_PORTS =
[HTTPS_PORT, HTTP_PORT]
DEFAULTS =
{
  headers: {},
  force_ssl: DEFAULT_FORCE_SSL,
}.freeze

Instance Method Summary collapse

Instance Method Details

#call(method, url, **opts) ⇒ Object



42
43
44
45
46
47
48
49
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/ree_lib/packages/ree_http/package/ree_http/functions/build_request.rb', line 42

def call(method, url, **opts)
  unless opts[:body].nil?
    unless  opts[:form_data].nil?
      raise ArgumentError, "You can't use body argument with form_data argument"
    end
  end

  opts = DEFAULTS.merge(opts)
  uri = URI(url)

  uri.scheme = opts[:force_ssl] ? HTTPS_STR : uri.scheme

  if DEFAULT_PROTOCOL_PORTS.include?(uri.port)
    uri.port = opts[:force_ssl] ? HTTPS_PORT : uri.port
  end

  q_string = opts[:query_params] ? URI.encode_www_form(opts[:query_params]) : nil

  uri.query = if uri.query.nil?
    q_string
  else
    if not_blank(q_string)
      uri.query + '&' + q_string.to_s
    else
      uri.query
    end
  end

  request =
    case method
    when :get then Net::HTTP::Get.new(uri)
    when :post then Net::HTTP::Post.new(uri)
    when :put then Net::HTTP::Put.new(uri)
    when :delete then Net::HTTP::Delete.new(uri)
    when :patch then Net::HTTP::Patch.new(uri)
    when :head then Net::HTTP::Head.new(uri)
    when :options then Net::HTTP::Options.new(uri)
    else
      raise ArgumentError, "Unavailable rest method"
    end

  unless opts[:body].nil?
    request.body =
      case opts[:body]
      when Hash then to_json(opts[:body])
      when File then opts[:body].read
      else
        opts[:body]
      end
  end

  unless opts[:form_data].nil?
    request = add_form_data(request, opts[:form_data])
  end

  opts[:headers].each do |k, v|
    request.add_field k, v
  end

  unless opts[:basic_auth].nil?
    request.basic_auth(opts[:basic_auth][:username], opts[:basic_auth][:password])
  end

  unless opts[:bearer_token].nil?
    request.add_field "Authorization", generate_bearer_auth(opts[:bearer_token])
  end

  request
end