Module: JRPC::Message

Defined in:
lib/jrpc/message.rb

Class Method Summary collapse

Class Method Details

.build_notification(method, params) ⇒ Object



14
15
16
17
18
19
# File 'lib/jrpc/message.rb', line 14

def self.build_notification(method, params)
  validate_params!(method, params)
  envelope = { 'jsonrpc' => JRPC::JSON_RPC_VERSION, 'method' => method.to_s }
  envelope['params'] = params unless params.nil?
  envelope
end

.build_request(method, params, id) ⇒ Object



7
8
9
10
11
12
# File 'lib/jrpc/message.rb', line 7

def self.build_request(method, params, id)
  validate_params!(method, params)
  envelope = { 'jsonrpc' => JRPC::JSON_RPC_VERSION, 'method' => method.to_s, 'id' => id }
  envelope['params'] = params unless params.nil?
  envelope
end

.dump(envelope) ⇒ Object



21
22
23
# File 'lib/jrpc/message.rb', line 21

def self.dump(envelope)
  JSON.generate(envelope)
end

.error_to_exception(error_hash) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/jrpc/message.rb', line 52

def self.error_to_exception(error_hash)
  code = error_hash['code']
  message = error_hash['message']
  case code
  when -32_700 then Errors::ParseError.new(message)
  when -32_600 then Errors::InvalidRequest.new(message)
  when -32_601 then Errors::MethodNotFound.new(message)
  when -32_602 then Errors::InvalidParams.new(message)
  when -32_603 then Errors::InternalError.new(message)
  when -32_099..-32_000 then Errors::InternalServerError.new(message, code: code)
  else Errors::UnknownError.new(message, code: code)
  end
end

.parse(json_string) ⇒ Object



25
26
27
28
29
# File 'lib/jrpc/message.rb', line 25

def self.parse(json_string)
  JSON.parse(json_string)
rescue JSON::ParserError => e
  raise Errors::MalformedResponseError, "JSON parse error: #{e.message}"
end

.validate_response!(hash, expected_id) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/jrpc/message.rb', line 31

def self.validate_response!(hash, expected_id)
  raise Errors::MalformedResponseError, 'response must be a Hash' unless hash.is_a?(Hash)
  raise Errors::MalformedResponseError, "jsonrpc must be #{JRPC::JSON_RPC_VERSION.inspect}" unless hash['jsonrpc'] == JRPC::JSON_RPC_VERSION
  unless hash['id'] == expected_id
    raise Errors::MalformedResponseError, "id mismatch: expected #{expected_id.inspect}, got #{hash['id'].inspect}"
  end

  has_result = hash.key?('result')
  has_error = hash.key?('error')
  unless has_result ^ has_error
    raise Errors::MalformedResponseError, "response must have exactly one of 'result' or 'error'"
  end

  if has_error
    err = hash['error']
    raise Errors::MalformedResponseError, 'error must be a Hash' unless err.is_a?(Hash)
    raise Errors::MalformedResponseError, 'error.code must be an Integer' unless err['code'].is_a?(Integer)
    raise Errors::MalformedResponseError, 'error.message must be a String' unless err['message'].is_a?(String)
  end
end