Class: JsonRpcClient::Request

Inherits:
Object
  • Object
show all
Includes:
EM::Deferrable
Defined in:
lib/json-rpc-client.rb

Overview

This class makes a single request to the JSON-RPC service as a EventMachine::Deferrable. The deferrable object will give a successful callback in the result-part of the response. A unsuccessful request will set the deferred status as failed, and will not deliver a result only the JSON-RPC error object as a Hash.

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Request

Returns a new instance of Request.



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/json-rpc-client.rb', line 204

def initialize(params)
  service_uri = params[:service_uri]
  post_body = {
    method:  params[:method],
    params:  params[:params],
    id:      'jsonrpc',
    jsonrpc: '2.0',
  }.to_json

  http = EM::HttpRequest.new(service_uri).post :body => post_body
  JsonRpcClient.log(:debug, "NEW REQUEST: #{service_uri} --> #{post_body}", params[:logger])

  http.callback do |response|
    begin
      resp = JSON.parse(response.response, {symbolize_names: params[:symbolize_names]})
      JsonRpcClient.log(
        :debug,
        "REQUEST FINISH: #{service_uri} METHOD: #{params[:method]} RESULT: #{resp}",
        params[:logger]
      )

      if resp.has_key?(:error) || resp.has_key?("error")
        JsonRpcClient.log(
          :error,
          "Error in response from #{service_uri}: #{resp[:error]}",
           params[:logger]
        )
        self.set_deferred_status :failed, resp[:error] || resp["error"]
      end
      self.set_deferred_status :succeeded, resp[:result] || resp["result"]
    rescue JSON::ParserError => e
      JsonRpcClient.log(
        :error,
        "Got exception during parsing of #{response}: #{e}",
        params[:logger]
      )

      # Making an error object in the same style as a JSON RPC error.
      set_deferred_status :failed, {
        code:    JsonRpcClient::INVALID_JSON,
        message: e.message,
        data:    e
      }
    end
  end

  http.errback do |response|
    JsonRpcClient.log(:error, "Error in http request: #{response.error}", params[:logger])
    set_deferred_status :failed, {
      code: JsonRpcClient::INVALID_JSON,
      message: response.error
    }
  end

  self
end