spectra_calendar_codec (spectra v0.11.2)
View SourceSummary
Functions
-spec decode(atom(), module(), spectra:sp_type_reference(), dynamic(), spectra:sp_type(), term(), spectra:sp_config()) -> spectra:codec_decode_result().
-spec encode(atom(), module(), spectra:sp_type_reference(), dynamic(), spectra:sp_type(), term(), spectra:sp_config()) -> spectra:codec_encode_result().
Built-in codec for calendar:datetime() and calendar:date().
Serialises to ISO 8601 strings and parses them back:
calendar:datetime()↔"YYYY-MM-DDTHH:MM:SSZ"(e.g."2024-01-15T10:30:00Z")calendar:date()↔"YYYY-MM-DD"(e.g."2024-01-15")
calendar:datetime() carries no timezone information — values are treated as
UTC. Encoding always appends Z; decoding requires the Z suffix and rejects
any other offset (e.g. +01:00).
If you need full timezone support, use a dedicated datetime library (e.g.
qdate or
calendar_extended) and implement
a custom spectra_codec behaviour for it.
Registering
Not active by default. Add to the application environment:
{spectra, [
{codecs, #{
{calendar, {type, datetime, 0}} => spectra_calendar_codec,
{calendar, {type, date, 0}} => spectra_calendar_codec
}}
]}Register only the types you use — registering both is fine, and each is independent.
Example
-type meeting() :: #{title => binary(), at => calendar:datetime()}.
DT = {{2024, 1, 15}, {10, 30, 0}},
{ok, Encoded} = spectra:encode(json, my_module, meeting, #{title => <<"Standup">>, at => DT}).
%% => {ok, <<"{\"title\":\"Standup\",\"at\":\"2024-01-15T10:30:00Z\"}">>}
{ok, Decoded} = spectra:decode(json, my_module, meeting, Encoded).
%% => {ok, #{title => <<"Standup">>, at => {{2024,1,15},{10,30,0}}}}
-spec schema(atom(), module(), spectra:sp_type_reference(), spectra:sp_type(), term(), spectra:sp_config()) -> dynamic().