Class: Lambda::MicroVMs::Endpoint

Inherits:
Object
  • Object
show all
Defined in:
lib/lambda/microvms/endpoint.rb

Overview

HTTP client for a single Lambda MicroVM endpoint.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url:, token:, http: Net::HTTP) ⇒ Endpoint

Returns a new instance of Endpoint.



13
14
15
16
17
# File 'lib/lambda/microvms/endpoint.rb', line 13

def initialize(url:, token:, http: Net::HTTP)
  @url = url
  @token = token
  @http = http
end

Instance Attribute Details

#urlObject (readonly)

Returns the value of attribute url.



11
12
13
# File 'lib/lambda/microvms/endpoint.rb', line 11

def url
  @url
end

Instance Method Details

#get(path, headers: {}) ⇒ Hash, ...

Send an authenticated GET request to the MicroVM endpoint.

Parameters:

  • path (String)

    endpoint path

  • headers (Hash) (defaults to: {})

    additional HTTP headers

Returns:

  • (Hash, String, nil)

    parsed JSON response or raw body



24
25
26
# File 'lib/lambda/microvms/endpoint.rb', line 24

def get(path, headers: {})
  request(Net::HTTP::Get, path, headers:)
end

#post(path, json: nil, body: nil, headers: {}) ⇒ Hash, ...

Send an authenticated POST request to the MicroVM endpoint.

Parameters:

  • path (String)

    endpoint path

  • json (Hash, Array, nil) (defaults to: nil)

    JSON body to encode

  • body (String, nil) (defaults to: nil)

    raw request body

  • headers (Hash) (defaults to: {})

    additional HTTP headers

Returns:

  • (Hash, String, nil)

    parsed JSON response or raw body



35
36
37
# File 'lib/lambda/microvms/endpoint.rb', line 35

def post(path, json: nil, body: nil, headers: {})
  request(Net::HTTP::Post, path, json:, body:, headers:)
end

#request(klass, path, json: nil, body: nil, headers: {}) ⇒ Hash, ...

Build and execute an authenticated HTTP request.

Parameters:

  • klass (Class)

    Net::HTTP request class

  • path (String)

    endpoint path

  • json (Hash, Array, nil) (defaults to: nil)

    JSON body to encode

  • body (String, nil) (defaults to: nil)

    raw request body

  • headers (Hash) (defaults to: {})

    additional HTTP headers

Returns:

  • (Hash, String, nil)

    parsed JSON response or raw body

Raises:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/lambda/microvms/endpoint.rb', line 48

def request(klass, path, json: nil, body: nil, headers: {})
  req = build_request(klass, path, headers:, body:, json:)
  response = @http.start(req.uri.host, req.uri.port, use_ssl: req.uri.scheme == 'https') do |http|
    http.request(req)
  end

  success = response.code.to_i.between?(200, 299)
  unless success
    raise EndpointError.new("MicroVM endpoint returned HTTP #{response.code}", status: response.code.to_i,
                                                                               body: response.body)
  end

  parse_response(response)
end