Module: Protip::Client

Extended by:
ActiveSupport::Concern
Defined in:
lib/protip/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#base_uriObject

Returns the value of attribute base_uri.



9
10
11
# File 'lib/protip/client.rb', line 9

def base_uri
  @base_uri
end

Instance Method Details

#request(path:, method:, message:, response_type:) ⇒ ::Protobuf::Message

Makes a request and parses the response as a message of the given type. For internal use only; use the appropriate resource to make your requests.

Parameters:

  • path (String)

    the URI path (exluding the base URI)

  • method (Class)

    the HTTP method (e.g. ‘::Net::HTTP::Get`, `::Net::HTTP::Post`)

  • message (Protobuf::Message|nil)

    the message to send as the request body

  • response_type (Class)

    the ‘::Protobuf::Message` subclass that should be expected as a response

Returns:

  • (::Protobuf::Message)

    the decoded response from the server

Raises:

  • (RuntimeError)


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/protip/client.rb', line 20

def request(path:, method:, message:, response_type:)

  raise RuntimeError.new('base_uri is not set') unless base_uri

  uri = URI.join base_uri, path

  request                 = method.new uri
  request.body            = (message ? message.class.encode(message) : nil)
  request['Accept']       = 'application/x-protobuf'
  request.content_type    = 'application/x-protobuf'

  prepare_request(request)

  # TODO: Shared connection object for persisent connections.
  response = execute_request(request)

  if response.is_a?(Net::HTTPUnprocessableEntity)
    raise ::Protip::UnprocessableEntityError.new(request, response)
  elsif response.is_a?(Net::HTTPNotFound)
    raise ::Protip::NotFoundError.new(request, response)
  elsif !response.is_a?(Net::HTTPSuccess)
    raise ::Protip::Error.new(request, response)
  end

  if response_type
    begin
      response_type.decode response.body
    rescue StandardError => error
      raise ::Protip::ParseError.new error, request, response
    end
  else
    nil
  end
end