class Twirp::ClientJSON

Convenience class to call any rpc method with dynamic json attributes, without a service definition. This is useful to test a service before doing any code-generation.

Public Class Methods

new(conn, opts={}) click to toggle source
Calls superclass method Twirp::Client::new
# File lib/twirp/client_json.rb, line 22
def initialize(conn, opts={})
  super(conn, opts)

  package = opts[:package].to_s
  service = opts[:service].to_s
  @strict = opts.fetch( :strict, false )
  raise ArgumentError.new("Missing option :service") if service.empty?
  @service_full_name = package.empty? ? service : "#{package}.#{service}"
end

Public Instance Methods

rpc(rpc_method, attrs={}, req_opts=nil) click to toggle source

This implementation does not use the defined Protobuf messages to serialize/deserialize data; the request attrs can be anything and the response data is always a plain Hash of attributes.

# File lib/twirp/client_json.rb, line 34
def rpc(rpc_method, attrs={}, req_opts=nil)
  body = Encoding.encode_json(attrs)

  encoding = @strict ? Encoding::JSON_STRICT : Encoding::JSON
  resp = self.class.make_http_request(@conn, @service_full_name, rpc_method, encoding, req_opts, body)
  if resp.status != 200
    return ClientResp.new(nil, self.class.error_from_response(resp))
  end

  data = Encoding.decode_json(resp.body)
  return ClientResp.new(data, nil)
end