retort v2.7.0 Retort.Request View Source

A JSON-RPC Request object

Link to this section Summary

Functions

Decodes a JSON-encoded string back to an t

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

Link to this section Types

Link to this type t() View Source
t() :: %Retort.Request{id: integer() | String.t() | nil, jsonrpc: String.t(), method: String.t(), params: [...] | map() | nil}

Link to this section Functions

Link to this function from_string(string) View Source
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)
Link to this function to_response(request) View Source
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