-module(lustre_http). -compile([no_auto_import, nowarn_unused_vars]). -export([get_as_text/2, get_as_json/3, post_text/3]). -export_type([http_error/0, http_or_json_error/0]). -type http_error() :: unauthorized | not_found | {internal_server_error, binary()} | {other_error, integer(), binary()}. -type http_or_json_error() :: {h, http_error()} | {j, gleam@json:decode_error()}. -spec decode_error(integer(), binary()) -> http_error(). decode_error(Code, Msg) -> case Code of 401 -> unauthorized; 404 -> not_found; 500 -> {internal_server_error, Msg}; _ -> {other_error, Code, Msg} end. -spec do_get( binary(), fun((binary()) -> nil), fun((integer(), binary()) -> nil) ) -> nil. do_get(Url, On_success, On_error) -> '.@ffi.mjs':do_request( <<"GET"/utf8>>, Url, <<""/utf8>>, On_success, On_error ). -spec do_post( binary(), binary(), fun((binary()) -> nil), fun((integer(), binary()) -> nil) ) -> nil. do_post(Url, Body, On_success, On_error) -> '.@ffi.mjs':do_request(<<"POST"/utf8>>, Url, Body, On_success, On_error). -spec get_as_text( binary(), fun(({ok, binary()} | {error, http_error()}) -> GRZ) ) -> lustre@cmd:cmd(GRZ). get_as_text(Url, To_msg) -> lustre@cmd:from( fun(Dispatch) -> do_get( Url, fun(Body) -> Dispatch(To_msg({ok, Body})) end, fun(Code, Msg) -> _pipe = decode_error(Code, Msg), _pipe@1 = {error, _pipe}, _pipe@2 = To_msg(_pipe@1), Dispatch(_pipe@2) end ) end ). -spec get_as_json( binary(), fun(({ok, binary()} | {error, http_or_json_error()}) -> GSF), fun((gleam@dynamic:dynamic()) -> {ok, binary()} | {error, list(gleam@dynamic:decode_error())}) ) -> lustre@cmd:cmd(GSF). get_as_json(Url, To_msg, Decoder) -> lustre@cmd:from( fun(Dispatch) -> do_get(Url, fun(Body) -> case gleam@json:decode(Body, Decoder) of {ok, Json} -> Dispatch(To_msg({ok, Json})); {error, Json_error} -> Dispatch(To_msg({error, {j, Json_error}})) end end, fun(Code, Msg) -> Http_error = case Code of 401 -> unauthorized; 404 -> not_found; 500 -> {internal_server_error, Msg}; _ -> {other_error, Code, Msg} end, Dispatch(To_msg({error, {h, Http_error}})) end) end ). -spec post_text( binary(), binary(), fun(({ok, binary()} | {error, http_error()}) -> GSI) ) -> lustre@cmd:cmd(GSI). post_text(Url, Body, To_msg) -> lustre@cmd:from( fun(Dispatch) -> do_post( Url, Body, fun(Body@1) -> Dispatch(To_msg({ok, Body@1})) end, fun(Code, Msg) -> _pipe = decode_error(Code, Msg), _pipe@1 = {error, _pipe}, _pipe@2 = To_msg(_pipe@1), Dispatch(_pipe@2) end ) end ).