Current section

Files

Jump to
oaspec src oaspec@openapi@value.erl
Raw

src/oaspec@openapi@value.erl

-module(oaspec@openapi@value).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/oaspec/openapi/value.gleam").
-export([from_node/1, extract_optional/2, extract_map/2, to_display_string/1]).
-export_type([json_value/0]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
-type json_value() :: json_null |
{json_bool, boolean()} |
{json_int, integer()} |
{json_float, float()} |
{json_string, binary()} |
{json_array, list(json_value())} |
{json_object, gleam@dict:dict(binary(), json_value())}.
-file("src/oaspec/openapi/value.gleam", 21).
?DOC(" Convert a yay.Node to a JsonValue.\n").
-spec from_node(yay:node_()) -> json_value().
from_node(Node) ->
case Node of
node_nil ->
json_null;
{node_str, S} ->
{json_string, S};
{node_bool, B} ->
{json_bool, B};
{node_int, I} ->
{json_int, I};
{node_float, F} ->
{json_float, F};
{node_seq, Items} ->
{json_array, gleam@list:map(Items, fun from_node/1)};
{node_map, Entries} ->
{json_object,
begin
_pipe = gleam@list:filter_map(
Entries,
fun(Entry) ->
{K, V} = Entry,
case K of
{node_str, Key} ->
{ok, {Key, from_node(V)}};
_ ->
{error, nil}
end
end
),
maps:from_list(_pipe)
end}
end.
-file("src/oaspec/openapi/value.gleam", 45).
?DOC(
" Try to extract a JsonValue from a node at a given key.\n"
" Returns None if the key is absent or nil.\n"
).
-spec extract_optional(yay:node_(), binary()) -> gleam@option:option(json_value()).
extract_optional(Node, Key) ->
case yay:select_sugar(Node, Key) of
{ok, node_nil} ->
none;
{ok, Child} ->
{some, from_node(Child)};
{error, _} ->
none
end.
-file("src/oaspec/openapi/value.gleam", 55).
?DOC(
" Extract a dict of JsonValues from a node at a given key.\n"
" Returns empty dict if key is absent.\n"
).
-spec extract_map(yay:node_(), binary()) -> gleam@dict:dict(binary(), json_value()).
extract_map(Node, Key) ->
case yay:select_sugar(Node, Key) of
{ok, {node_map, Entries}} ->
_pipe = gleam@list:filter_map(
Entries,
fun(Entry) ->
{K, V} = Entry,
case K of
{node_str, Name} ->
{ok, {Name, from_node(V)}};
_ ->
{error, nil}
end
end
),
maps:from_list(_pipe);
_ ->
maps:new()
end.
-file("src/oaspec/openapi/value.gleam", 71).
?DOC(" Convert a JsonValue to a display string (for error messages, not serialization).\n").
-spec to_display_string(json_value()) -> binary().
to_display_string(Value) ->
case Value of
json_null ->
<<"null"/utf8>>;
{json_bool, true} ->
<<"true"/utf8>>;
{json_bool, false} ->
<<"false"/utf8>>;
{json_int, I} ->
erlang:integer_to_binary(I);
{json_float, F} ->
gleam_stdlib:float_to_string(F);
{json_string, S} ->
S;
{json_array, _} ->
<<"[...]"/utf8>>;
{json_object, _} ->
<<"{...}"/utf8>>
end.