Class: Sinatra::JsonRpc::Handler
- Inherits:
-
Object
- Object
- Sinatra::JsonRpc::Handler
- Defined in:
- lib/json_rpc/handler.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
- #error(id, code, message) ⇒ Object
-
#initialize(app) ⇒ Handler
constructor
A new instance of Handler.
- #parse_request_object ⇒ Object
- #request_id ⇒ Object
- #request_method ⇒ Object
- #request_object ⇒ Object
- #request_params ⇒ Object
- #respond_with_error(request_id:, code:, message:) ⇒ Object
- #valid_rpc_method? ⇒ Boolean
Constructor Details
#initialize(app) ⇒ Handler
Returns a new instance of Handler.
6 7 8 |
# File 'lib/json_rpc/handler.rb', line 6 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/json_rpc/handler.rb', line 10 def call(env) @env = env unless valid_rpc_method? status, headers, body = @app.call(env) return [status, headers, body] end begin request_object @env["rack.logger"].info(request_object) @app.send request_method, request_params, request_id rescue NoMethodError raise if @app.available_methods.include?(request_method.to_sym) error request_id, -32_601, "Method not found" rescue JsonRpc::InvalidParametersError error request_id, -32_700, "Invalid params" rescue JSON::ParserError error nil, -32_700, "Parse error" end end |
#error(id, code, message) ⇒ Object
44 45 46 |
# File 'lib/json_rpc/handler.rb', line 44 def error(id, code, ) respond_with_error request_id: id, code: code, message: end |
#parse_request_object ⇒ Object
70 71 72 73 |
# File 'lib/json_rpc/handler.rb', line 70 def parse_request_object @env["rack.input"].rewind JSON[@env["rack.input"].read] end |
#request_id ⇒ Object
66 67 68 |
# File 'lib/json_rpc/handler.rb', line 66 def request_id request_object.fetch("id") end |
#request_method ⇒ Object
56 57 58 |
# File 'lib/json_rpc/handler.rb', line 56 def request_method request_object["method"] end |
#request_object ⇒ Object
48 49 50 |
# File 'lib/json_rpc/handler.rb', line 48 def request_object parse_request_object end |
#request_params ⇒ Object
60 61 62 63 64 |
# File 'lib/json_rpc/handler.rb', line 60 def request_params request_object.fetch("params") do {} end end |
#respond_with_error(request_id:, code:, message:) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/json_rpc/handler.rb', line 31 def respond_with_error(request_id:, code:, message:) error = { id: request_id, jsonrpc: "2.0", error: { code: code, message: } } [200, { "Content-type" => "application/json" }, error.to_json] end |
#valid_rpc_method? ⇒ Boolean
52 53 54 |
# File 'lib/json_rpc/handler.rb', line 52 def valid_rpc_method? @env["REQUEST_METHOD"] == "POST" && @env["PATH_INFO"] == "/api" end |