Class: JSONRPC::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonrpc/middleware.rb

Overview

Rack middleware for handling JSON-RPC 2.0 requests

This middleware intercepts HTTP POST requests at a specified path and processes them as JSON-RPC 2.0 messages. It handles parsing, validation, and error responses according to the JSON-RPC 2.0 specification.

Examples:

Basic usage

use JSONRPC::Middleware

Custom path

use JSONRPC::Middleware, path: '/api/v1/rpc'

Constant Summary collapse

DEFAULT_PATH =

Default path for JSON-RPC requests

Returns:

  • (String)

    The default path ‘/’

'/'

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Initializes the JSON-RPC middleware

Examples:

Basic initialization

middleware = JSONRPC::Middleware.new(app)

With custom path

middleware = JSONRPC::Middleware.new(app, path: '/api/jsonrpc')

Parameters:

  • app (#call)

    The Rack application to wrap

  • options (Hash) (defaults to: {})

    Configuration options

Options Hash (options):

  • :path (String) — default: '/'

    The path to handle JSON-RPC requests on

  • :rescue_internal_errors (Boolean) — default: nil

    Override config rescue_internal_errors

  • :log_internal_errors (Boolean) — default: true

    Override config log_internal_errors



45
46
47
48
49
50
51
52
53
# File 'lib/jsonrpc/middleware.rb', line 45

def initialize(app, options = {})
  @app = app
  @parser = Parser.new
  @validator = Validator.new
  @path = options.fetch(:path, DEFAULT_PATH)
  @config = JSONRPC.configuration
  @log_internal_errors = options.fetch(:log_internal_errors, @config.log_internal_errors)
  @rescue_internal_errors = options.fetch(:rescue_internal_errors, @config.rescue_internal_errors)
end

Instance Method Details

#call(env) ⇒ Array

Rack application call method

Examples:

Processing a request

status, headers, body = middleware.call(env)

Parameters:

  • env (Hash)

    The Rack environment

Returns:

  • (Array)

    Rack response tuple [status, headers, body]



66
67
68
69
70
71
72
73
74
# File 'lib/jsonrpc/middleware.rb', line 66

def call(env)
  @req = Rack::Request.new(env)

  if jsonrpc_request?
    handle_jsonrpc_request
  else
    @app.call(env)
  end
end