retort v2.1.0 Retort.Request

A JSON-RPC Request object

Summary

Functions

Decodes a JSON-encoded string back to an t

Constructs Interpreter.Rpc.Response.t with same id as the given response

Types

t()
t() :: %Retort.Request{id: integer | String.t | nil, jsonrpc: String.t, method: String.t, params: [...] | map | nil}

Functions

from_string(string)
from_string(String.t) ::
  {:ok, t} |
  {:error, :invalid} |
  {:error, {:invalid, token :: String.t}} |
  {:error, :invalid, position :: non_neg_integer} |
  {:error, {:invalid, token :: String.t, position :: non_neg_integer}}

Decodes a JSON-encoded string back to an t.

Decode method without parameters

iex> {:ok, request} = Retort.Request.from_string(
...>                    ~S|{"jsonrpc": "2.0", "id": 1, "method": "index"}|
...>                  )
iex> request
%Retort.Request{jsonrpc: "2.0", id: 1, method: "index"}

Decode method with positional arguments

iex> {:ok, request} = Retort.Request.from_string(
...>                    ~S|{"jsonrpc": "2.0", "id": 2, "method": "show", "params": [1]}|
...>                  )
iex> request
%Retort.Request{jsonrpc: "2.0", id: 2, method: "show", params: [1]}

Decode method with named arguments

iex> {:ok, request} = Retort.Request.from_string(
...>                    ~S|{"jsonrpc": "2.0", "id": 3, "method": "create", "params": {"name": "Alice"}}|
...>                  )
iex> request
%Retort.Request{jsonrpc: "2.0", id: 3, method: "create", params: %{"name" => "Alice"}}

Decode with missing fields is OK

iex> {:ok, request} = Retort.Request.from_string("{}")
iex> request
%Retort.Request{}

Proper handling of all return values

# See http://www.jsonrpc.org/specification#examples
response = case Retort.Request.from_string(encoded_request) do
             {:ok, request = %Retort.Request{}} ->
               response_for(request)
             {:error, :invalid} ->
               %Retort.Response{
                 error: %Retort.Response.Error{
                          code: -32600,
                          message: "Invalid Request"
                        }
               }
             {:error, {:invalid, token}} ->
               %Retort.Response{
                 error: %Retort.Response.Error{
                          code: -32700,
                          message: "Parse error"
                        }
               }
           end
encoded_response = Poison.encode!(response)
to_response(request)
to_response(t) :: Retort.Response.t

Constructs Interpreter.Rpc.Response.t with same id as the given response.

iex> request = %Retort.Request{id: 1}
iex> response = Retort.Request.to_response(request)
iex> response.id == request.id
true