Class: Code::Object::Http

Inherits:
Code::Object show all
Defined in:
lib/code/object/http.rb

Constant Summary collapse

SIG =
[
  String,
  {
    headers: Dictionary.maybe,
    query: Dictionary.maybe,
    body: String.maybe,
    username: String.maybe,
    password: String.maybe,
    data: Dictionary.maybe,
    timeout: (Integer | Decimal).maybe,
    open_timeout: (Integer | Decimal).maybe,
    read_timeout: (Integer | Decimal).maybe,
    write_timeout: (Integer | Decimal).maybe
  }
].freeze
STATUS_CODES =
{
  continue: 100,
  switching_protocols: 101,
  processing: 102,
  early_hints: 103,
  ok: 200,
  created: 201,
  accepted: 202,
  non_authoritative_information: 203,
  no_content: 204,
  reset_content: 205,
  partial_content: 206,
  multi_status: 207,
  already_reported: 208,
  im_used: 226,
  multiple_choices: 300,
  moved_permanently: 301,
  found: 302,
  see_other: 303,
  not_modified: 304,
  use_proxy: 305,
  reserved: 306,
  temporary_redirect: 307,
  permanent_redirect: 308,
  bad_request: 400,
  unauthorized: 401,
  payment_required: 402,
  forbidden: 403,
  not_found: 404,
  method_not_allowed: 405,
  not_acceptable: 406,
  proxy_authentication_required: 407,
  request_timeout: 408,
  conflict: 409,
  gone: 410,
  length_required: 411,
  precondition_failed: 412,
  request_entity_too_large: 413,
  request_uri_too_long: 414,
  unsupported_media_type: 415,
  requested_range_not_satisfiable: 416,
  expectation_failed: 417,
  misdirected_request: 421,
  unprocessable_entity: 422,
  locked: 423,
  failed_dependency: 424,
  too_early: 425,
  upgrade_required: 426,
  precondition_required: 428,
  too_many_requests: 429,
  request_header_fields_too_large: 431,
  unavailable_for_legal_reasons: 451,
  internal_server_error: 500,
  not_implemented: 501,
  bad_gateway: 502,
  service_unavailable: 503,
  gateway_timeout: 504,
  http_version_not_supported: 505,
  variant_also_negotiates: 506,
  insufficient_storage: 507,
  loop_detected: 508,
  bandwidth_limit_exceeded: 509,
  not_extended: 510,
  network_authentication_required: 511
}.freeze
DEFAULT_TIMEOUT =
1.hour.to_f

Constants inherited from Code::Object

NUMBER_CLASSES

Instance Attribute Summary

Attributes included from Concerns::Shared

#methods, #raw

Class Method Summary collapse

Methods inherited from Code::Object

code_new, #code_new, #initialize, maybe, #name, repeat, |

Methods included from Concerns::Shared

#<=>, #==, #as_json, #blank?, #call, #code_and, #code_as_json, #code_blank?, #code_compare, #code_deep_duplicate, #code_different, #code_duplicate, #code_equal, #code_exclamation_mark, #code_exclusive_range, #code_falsy?, #code_fetch, #code_get, #code_greater, #code_greater_or_equal, #code_inclusive_range, #code_inspect, #code_less, #code_less_or_equal, #code_methods, #code_name, #code_nothing?, #code_or, #code_presence, #code_presence_in, #code_present?, #code_self, #code_set, code_set, #code_something?, #code_strict_different, #code_strict_equal, #code_to_boolean, #code_to_class, #code_to_date, #code_to_decimal, #code_to_dictionary, #code_to_duration, #code_to_integer, #code_to_json, #code_to_list, #code_to_nothing, #code_to_parameter, #code_to_range, #code_to_string, #code_to_time, #code_truthy?, #eql?, #falsy?, #hash, #inspect, #multi_fetch, #nothing?, #present?, #sig, #something?, #succ, #to_code, #to_i, #to_json, #to_s, #truthy?

Constructor Details

This class inherits a constructor from Code::Object

Class Method Details

.call(**args) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/code/object/http.rb', line 89

def self.call(**args)
  code_operator = args.fetch(:operator, nil).to_code
  code_arguments = args.fetch(:arguments, []).to_code

  case code_operator.to_s
  when "get"
    sig(args) { SIG }
    code_get(*code_arguments.raw)
  when "head"
    sig(args) { SIG }
    code_head(*code_arguments.raw)
  when "post"
    sig(args) { SIG }
    code_post(*code_arguments.raw)
  when "put"
    sig(args) { SIG }
    code_put(*code_arguments.raw)
  when "delete"
    sig(args) { SIG }
    code_delete(*code_arguments.raw)
  when "options"
    sig(args) { SIG }
    code_options(*code_arguments.raw)
  when "trace"
    sig(args) { SIG }
    code_trace(*code_arguments.raw)
  when "patch"
    sig(args) { SIG }
    code_patch(*code_arguments.raw)
  when "fetch"
    sig(args) { [String] + SIG }
    code_fetch(*code_arguments.raw)
  else
    super
  end
end

.code_deleteObject



142
143
144
# File 'lib/code/object/http.rb', line 142

def self.code_delete(...)
  code_fetch("delete", ...)
end

.code_fetch(*arguments, redirects: 10) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/code/object/http.rb', line 158

def self.code_fetch(*arguments, redirects: 10)
  verb = arguments.first.to_code.to_s.downcase
  original_url = arguments.second.to_code.to_s
  options = arguments.third.to_code
  options = Dictionary.new if options.nothing?
  username = options.code_get("username").to_s
  password = options.code_get("password").to_s
  body = options.code_get("body").to_s
  headers = options.code_get("headers").raw || {}
  data = options.code_get("data").raw || {}
  timeout = options.code_get("timeout")
  open_timeout = options.code_get("open_timeout")
  read_timeout = options.code_get("read_timeout")
  write_timeout = options.code_get("write_timeout")
  query = options.code_get("query").raw || {}
  query = query.to_a.flatten.map(&:to_s).each_slice(2).to_h.to_query

  url = original_url
  url = "#{url}?#{query}" if query.present?

  if username.present? || password.present?
    authorization = ::Base64.strict_encode64("#{username}:#{password}")
    headers["Authorization"] = "Basic #{authorization}"
  end

  uri = ::URI.parse(url)
  http = ::Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true if uri.scheme == "https"
  default_timeout = timeout.nothing? ? DEFAULT_TIMEOUT : timeout.to_f
  open_timeout_value = open_timeout.nothing? ? default_timeout : open_timeout.to_f
  read_timeout_value = read_timeout.nothing? ? default_timeout : read_timeout.to_f
  write_timeout_value = write_timeout.nothing? ? default_timeout : write_timeout.to_f

  http.open_timeout = open_timeout_value if open_timeout_value
  http.read_timeout = read_timeout_value if read_timeout_value
  if http.respond_to?(:write_timeout=) && write_timeout_value
    http.write_timeout = write_timeout_value
  end

  request_class =
    case verb
    when "head"
      ::Net::HTTP::Head
    when "post"
      ::Net::HTTP::Post
    when "put"
      ::Net::HTTP::Put
    when "delete"
      ::Net::HTTP::Delete
    when "options"
      ::Net::HTTP::Options
    when "trace"
      ::Net::HTTP::Trace
    when "patch"
      ::Net::HTTP::Patch
    else
      ::Net::HTTP::Get
    end

  request = request_class.new(uri)
  headers.each { |key, value| request[key.to_s] = value.to_s }
  request.body = body if body.present?
  request.set_form_data(**data.as_json) if data.present?

  begin
    response = http.request(request)
  rescue ::Timeout::Error,
         ::Net::OpenTimeout,
         ::Net::ReadTimeout,
         ::Errno::ETIMEDOUT
    raise ::Code::Error, "http timeout"
  rescue OpenSSL::SSL::SSLError, IOError, EOFError
    raise ::Code::Error, "http error"
  end

  code = response.code.to_i
  location = response["location"].to_s

  if (300..399).cover?(code) && location.present? && redirects.positive?
    new_uri = ::URI.join(uri, location)

    if new_uri.host == uri.host
      code_fetch(
        "get",
        new_uri.to_s,
        { username: username, password: password, headers: headers },
        redirects: redirects - 1
      )
    else
      code_fetch("get", new_uri.to_s, redirects: redirects - 1)
    end
  else
    status = STATUS_CODES.key(code) || :ok
    Dictionary.new(code: code, status: status, body: response.body.to_s)
  end
end

.code_getObject



126
127
128
# File 'lib/code/object/http.rb', line 126

def self.code_get(...)
  code_fetch("get", ...)
end

.code_headObject



130
131
132
# File 'lib/code/object/http.rb', line 130

def self.code_head(...)
  code_fetch("head", ...)
end

.code_optionsObject



146
147
148
# File 'lib/code/object/http.rb', line 146

def self.code_options(...)
  code_fetch("options", ...)
end

.code_patchObject



154
155
156
# File 'lib/code/object/http.rb', line 154

def self.code_patch(...)
  code_fetch("patch", ...)
end

.code_postObject



134
135
136
# File 'lib/code/object/http.rb', line 134

def self.code_post(...)
  code_fetch("post", ...)
end

.code_putObject



138
139
140
# File 'lib/code/object/http.rb', line 138

def self.code_put(...)
  code_fetch("put", ...)
end

.code_traceObject



150
151
152
# File 'lib/code/object/http.rb', line 150

def self.code_trace(...)
  code_fetch("trace", ...)
end