Class: JSONRPC::Response

Inherits:
Dry::Struct
  • Object
show all
Defined in:
lib/jsonrpc/response.rb

Overview

A JSON-RPC 2.0 Response object

Represents the outcome of a method invocation, either containing a result for successful calls or an error for failed ones. This follows the JSON-RPC 2.0 specification.

When a rpc call is made, the Server must reply with a Response, except for notifications. A Response object can contain either a result (for success) or an error (for failure), but never both.

Examples:

Create a successful response

response = JSONRPC::Response.new(result: 19, id: 1)

Create an error response

error = JSONRPC::Error.new(code: -32601, message: "Method not found")
response = JSONRPC::Response.new(error: error, id: 1)

Instance Method Summary collapse

Instance Method Details

#errorJSONRPC::Error?

The error object (for failure)

Examples:

response.error # => #<JSONRPC::Error...>

Returns:



56
# File 'lib/jsonrpc/response.rb', line 56

attribute? :error, Types.Instance(JSONRPC::Error).optional

#error?Boolean

Checks if the response is an error

Examples:

response.error? # => false

Returns:

  • (Boolean)

    true if the response contains an error, false if it contains a result



113
114
115
# File 'lib/jsonrpc/response.rb', line 113

def error?
  !error.nil?
end

#idString, ...

The request identifier

Examples:

response.id # => 1

Returns:

  • (String, Integer, nil)


67
# File 'lib/jsonrpc/response.rb', line 67

attribute? :id, Types::String | Types::Integer | Types::Nil

#jsonrpcString

JSON-RPC protocol version

Examples:

response.jsonrpc # => "2.0"

Returns:

  • (String)


34
# File 'lib/jsonrpc/response.rb', line 34

attribute :jsonrpc, Types::String.default('2.0')

#resultObject?

The result of the method invocation (for success)

Examples:

response.result # => 42

Returns:

  • (Object, nil)


45
# File 'lib/jsonrpc/response.rb', line 45

attribute? :result, Types::Any

#success?Boolean

Checks if the response is successful

Examples:

response.success? # => true

Returns:

  • (Boolean)

    true if the response contains a result, false if it contains an error



100
101
102
# File 'lib/jsonrpc/response.rb', line 100

def success?
  !result.nil?
end

#to_hHash

Converts the response to a JSON-compatible Hash

Examples:

response.to_h # => { jsonrpc: "2.0", result: 42, id: 1 }

Returns:

  • (Hash)

    the response as a JSON-compatible Hash



126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/jsonrpc/response.rb', line 126

def to_h
  hash = {
    jsonrpc: jsonrpc,
    id: id
  }

  if success?
    hash[:result] = result
  else
    hash[:error] = error.to_h
  end

  hash
end

#to_jsonString

Converts the response to a JSON string

Examples:

response.to_json # => '{"jsonrpc":"2.0","result":42,"id":1}'

Returns:

  • (String)

    the response as a JSON string



150
151
152
# File 'lib/jsonrpc/response.rb', line 150

def to_json(*)
  MultiJson.dump(to_h, *)
end