JSONRPC2.Plug (jsonrpc2_plug v2.1.0)

Copy Markdown

JSONRPC2.Plug

An Elixir plug library for extending an HTTP server with JSONRPC 2.0 protocol services. It's HTTP transport level. For use both in the Phoenix application and pure plug-compatable server.

Installation

The package can be installed by adding jsonrpc2_plug to your list of dependencies in mix.exs:

def deps do
  [
    {:jsonrpc2_plug, "~> 2.0.0"}
  ]
end

Usage

Services

It uses jsonrpc2_service library for service creation.

Pure plug-compatable server

use Plug.Router

forward "/jsonrpc", to: JSONRPC2.Plug, init_opts: CalculatorService

CalculatorService is a service build by jsonrpc2_service library

You can handle errors outside of plug. Add Plug.ErrorHandler into a router and define &handle_errors/2 function (read more).

  use Plug.ErrorHandler

  @impl Plug.ErrorHandler
  def handle_errors(conn, %{kind: kind, reason: reason, stack: stacktrace}) do
    kind |> Exception.format(reason, stacktrace) |> Logger.error()

    case conn do
      %{request_path: "/jsonrpc"} ->
        JSONRPC2.Plug.send_error(conn, kind, reason)

      _ ->
        send_resp(conn, 500, "Someting went wrong")
    end
  end

Phoenix server


forward "/jsonrpc", JSONRPC2.Plug, CalculatorService

Documentation can be generated with ExDoc and published on HexDocs. Once published, the docs can be found at https://hexdocs.pm/jsonrpc2_plug.

Summary

Functions

HTTP entry point to JSONRPC 2.0 services. It's usual plug and accepts service handler module as a param.

Send an error encoded according to JSONRPC 2.0 spec. It can be useful for global error handler in the router.

Functions

call(conn, handler)

@spec call(Plug.Conn.t(), Plug.opts()) :: Plug.Conn.t()

HTTP entry point to JSONRPC 2.0 services. It's usual plug and accepts service handler module as a param.

Example:

use Plug.Router

forward "/jsonrpc", to: JSONRPC2.Plug, init_opts: CalculatorService

send_error(conn, kind, ex)

@spec send_error(Plug.Conn.t(), atom(), struct()) :: Plug.Conn.t()

Send an error encoded according to JSONRPC 2.0 spec. It can be useful for global error handler in the router.

Example:

forward "/jsonrpc", to: JSONRPC2.Plug, init_opts: CalculatorService

@impl Plug.ErrorHandler
def handle_errors(conn, %{kind: kind, reason: reason, stack: stacktrace}) do
  Logger.error(Exception.format(kind, reason, stacktrace))

  case conn do
    %{request_path: "/jsonrpc"} ->
      JSONRPC2.Plug.send_error(conn, kind, reason)

    _ ->
      send_resp(conn, 500, "Someting went wrong")
  end
end