-module(plunk@internal@bridge). -compile([no_auto_import, nowarn_unused_vars]). -export([normalize_path/1, make_request/4, error_decoder/0, decode/2]). -spec set_header(gleam@http@request:request(binary()), binary(), binary()) -> gleam@http@request:request(binary()). set_header(Req, Key, Value) -> erlang:setelement(3, Req, [{Key, Value} | erlang:element(3, Req)]). -spec normalize_path(binary()) -> binary(). normalize_path(Path) -> Path@1 = case gleam@string:starts_with(Path, <<"/"/utf8>>) of true -> Path; false -> <<"/"/utf8, Path/binary>> end, case gleam@string:ends_with(Path@1, <<"/"/utf8>>) of true -> _pipe = Path@1, _pipe@1 = gleam@string:trim(_pipe), gleam@string:drop_right(_pipe@1, 1); false -> Path@1 end. -spec make_request( plunk@instance:instance(), binary(), gleam@http:method(), binary() ) -> gleam@http@request:request(binary()). make_request(Instance, Path, Method, Body) -> _pipe = gleam@http@request:new(), _pipe@1 = gleam@http@request:set_method(_pipe, Method), _pipe@2 = gleam@http@request:set_host(_pipe@1, <<"api.useplunk.com"/utf8>>), _pipe@3 = gleam@http@request:set_path( _pipe@2, <<"/v1"/utf8, (normalize_path(Path))/binary>> ), _pipe@4 = (fun(Request) -> case Method of get -> Request; _ -> gleam@http@request:set_body(Request, Body) end end)(_pipe@3), _pipe@5 = set_header( _pipe@4, <<"Content-Type"/utf8>>, <<"application/json"/utf8>> ), _pipe@6 = set_header( _pipe@5, <<"Accept"/utf8>>, <<"application/json"/utf8>> ), set_header( _pipe@6, <<"Authorization"/utf8>>, <<"Bearer "/utf8, (erlang:element(2, Instance))/binary>> ). -spec error_decoder() -> fun((gleam@dynamic:dynamic_()) -> {ok, plunk@types:plunk_error()} | {error, list(gleam@dynamic:decode_error())}). error_decoder() -> gleam@dynamic:decode4( fun(Field@0, Field@1, Field@2, Field@3) -> {api_error, Field@0, Field@1, Field@2, Field@3} end, gleam@dynamic:field(<<"code"/utf8>>, fun gleam@dynamic:int/1), gleam@dynamic:field(<<"error"/utf8>>, fun gleam@dynamic:string/1), gleam@dynamic:field(<<"message"/utf8>>, fun gleam@dynamic:string/1), gleam@dynamic:field(<<"time"/utf8>>, fun gleam@dynamic:int/1) ). -spec decode( gleam@http@response:response(binary()), fun(() -> fun((gleam@dynamic:dynamic_()) -> {ok, IQS} | {error, list(gleam@dynamic:decode_error())})) ) -> {ok, IQS} | {error, plunk@types:plunk_error()}. decode(Res, Decoder) -> {response, Status, _, Body} = Res, case Status of Status@1 when (Status@1 >= 200) andalso (Status@1 < 300) -> case gleam@json:decode(Body, Decoder()) of {ok, Decoded} -> {ok, Decoded}; {error, Err} -> {error, {json_error, Err}} end; _ -> case gleam@json:decode(Body, error_decoder()) of {ok, Decoded@1} -> {error, Decoded@1}; {error, Err@1} -> {error, {json_error, Err@1}} end end.