Class: OpenC3::JsonRpcResponse

Inherits:
JsonRpc show all
Defined in:
lib/openc3/io/json_rpc.rb

Overview

Represents a JSON Remote Procedure Call Response

Direct Known Subclasses

JsonRpcErrorResponse, JsonRpcSuccessResponse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from JsonRpc

#<=>, #as_json, #to_json

Constructor Details

#initialize(id) ⇒ JsonRpcResponse

Returns a new instance of JsonRpcResponse.

Parameters:

  • id (Integer)

    The identifier which will be matched to the request



293
294
295
296
297
# File 'lib/openc3/io/json_rpc.rb', line 293

def initialize(id)
  super()
  @hash['jsonrpc'.freeze] = "2.0".freeze
  @hash['id'.freeze] = id
end

Class Method Details

.from_json(response_data) ⇒ JsonRpcResponse

Creates a JsonRpcResponse object from a JSON encoded String. The version must be 2.0 and the JSON must include the id members. It must also include either result for success or error for failure but never both.

Parameters:

  • response_data (String)

    JSON encoded string representing the response

Returns:



305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/openc3/io/json_rpc.rb', line 305

def self.from_json(response_data)
  msg = "Invalid JSON-RPC 2.0 Response#{response_data.inspect}\n"
  begin
    hash = JSON.parse(response_data, :allow_nan => true, :create_additions => true)
  rescue
    raise $!, msg, $!.backtrace
  end

  # Verify the jsonrpc version is correct and there is an ID
  raise msg unless hash['jsonrpc'.freeze] == "2.0".freeze and hash.key?('id'.freeze)

  # If there is a result this is probably a good response
  if hash.key?('result'.freeze)
    # Can't have an error key in a good response
    raise msg if hash.key?('error'.freeze)

    JsonRpcSuccessResponse.from_hash(hash)
  elsif hash.key?('error'.freeze)
    # There was an error key so create an error response
    JsonRpcErrorResponse.from_hash(hash)
  else
    # Neither a result or error key so raise exception
    raise msg
  end
end