diff --git a/src/hz_grids.erl b/src/hz_grids.erl index 17482c7..7e54aa1 100644 --- a/src/hz_grids.erl +++ b/src/hz_grids.erl @@ -38,7 +38,7 @@ -module(hz_grids). -vsn("0.7.0"). --export([url/2, parse/1, req/2, req/3]). +-export([url/2, url/3, url/4, parse/1, req/2, req/3]). -spec url(Instruction, HTTP) -> Result @@ -66,17 +66,57 @@ url2(Instruction, URL = #{path := Path}) -> {ok, uri_string:recompose(GRIDS)}. --spec url(Instruction, Context, Recipient, Payload, Amount) -> Result - when Instruction :: spend | transfer, - Context :: uri_string:uri_string() | string(), % +-spec url(Instruction, Recipient, Amount) -> GRIDS + when Instruction :: {spend, Network} | {transfer, Node}, + Network :: string(), + Node :: {inet:ip_address() | inet:hostname(), inet:port_number()} + | uri_string:uri_string(), Recipient :: string(), - Payload :: binary(), Amount :: non_neg_integer(), - Result :: {ok, GRIDS} | error | uri_string:uri_error(). + GRIDS :: uri_string:uri_string(). +%% @doc +%% Forms a GRIDS URL for spends or transfers. +%% @equiv uri(Instruction, Recipient, Amount, ""). -url(spend, Context, Recipient, Payload, Amount) -> - url(spend, -url(transfer, Context, Recipient, Payload, Amount) -> +url(Instruction, Recipient, Amount) -> + url(Instruction, Recipient, Amount, ""). + + +-spec url(Instruction, Recipient, Amount, Payload) -> GRIDS + when Instruction :: {spend, Network} | {transfer, Node}, + Network :: string(), + Node :: {inet:ip_address() | inet:hostname(), inet:port_number()} + | uri_string:uri_string(), % "http://..." | "https://..." + Recipient :: string(), + Amount :: non_neg_integer(), + Payload :: binary(), + GRIDS :: uri_string:uri_string(). +%% @doc +%% Forms a GRIDS URL for spends or transfers. + +url({spend, Network}, Recipient, Amount, Payload) -> + Elements = ["grids://", Network, "/1/s/", Recipient, qwargs(Amount, Payload)], + unicode:characters_to_list(Elements); +url({transfer, Node}, Recipient, Amount, Payload) -> + Prefix = + case Node of + {H, P} -> ["grid://", h_to_s(H), ":", integer_to_list(P)]; + "https://" ++ H -> ["grids://", H]; + "http://" ++ H -> ["grid://", H]; + <<"https://", H/binary>> -> ["grids://", H]; + <<"http://", H/binary>> -> ["grid://", H] + end, + unicode:characters_to_list([Prefix, "/1/t/", Recipient, qwargs(Amount, Payload)]). + +h_to_s(Host) when is_list(Host) -> Host; +h_to_s(Host) when is_binary(Host) -> Host; +h_to_s(Host) when is_tuple(Host) -> inet:ntoa(Host); +h_to_s(Host) when is_atom(Host) -> atom_to_list(Host). + +qwargs(Amount, "") -> + ["?a=", integer_to_list(Amount)]; +qwargs(Amount, Payload) -> + [$? | uri_string:compose_query([{"a", integer_to_list(Amount)}, {"p", Payload}])]. -spec parse(GRIDS) -> Result