Skip to content

Commit

Permalink
Merge pull request #92 from davydog187/encode-nils
Browse files Browse the repository at this point in the history
Encode nil as null
  • Loading branch information
mikpe authored Jan 31, 2020
2 parents 3dcb4a9 + 1a5e382 commit ebdee67
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,5 @@
based on `record_type` and `map_type` options.
* 2.8.1
- Support 'object' as custom type properties
* 2.8.2
- Encode atom `nil` as "null" for Elixir consumers
3 changes: 3 additions & 0 deletions src/avro_primitive.erl
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ string_type() -> type(?AVRO_STRING, []).
-spec cast(avro_type(), term()) -> {ok, avro_value()} | {error, term()}.
cast(Type, null) when ?IS_NULL_TYPE(Type) ->
{ok, ?AVRO_VALUE(Type, null)};
% For Elixir compatibility
cast(Type, nil) when ?IS_NULL_TYPE(Type) ->
{ok, ?AVRO_VALUE(Type, null)};
cast(Type, Value) when ?IS_BOOLEAN_TYPE(Type) andalso
is_boolean(Value) ->
{ok, ?AVRO_VALUE(Type, Value)};
Expand Down
2 changes: 1 addition & 1 deletion src/erlavro.app.src
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{application, erlavro,
[
{description, "Apache Avro support for Erlang/Elixir"},
{vsn, "2.8.1"},
{vsn, "2.8.2"},
{registered, []},
{applications, [
kernel,
Expand Down
29 changes: 29 additions & 0 deletions test/avro_tests.erl
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,35 @@ default_values_test() ->
TestFun([{encoding, avro_json}]),
ok.

nil_values_test() ->
File = filename:join(priv_dir(), "test.avsc"),
{ok, JSON} = file:read_file(File),
Type = avro:decode_schema(JSON),
Lkup = avro:make_lkup_fun(Type),
%% Encode input has no 'children' field, default value should be used
Input = [{"f1", [{"label", "x"}]}, {"f2", nil}, {"f3", nil}],
Expect = [{<<"f1">>, [ {<<"label">>, <<"x">>}
, {<<"children">>,
[ [ {<<"label">>, <<"default-label">>}
, {<<"children">>, []}
]
]}
]},
{<<"f2">>, null},
{<<"f3">>, null}],
TestFun =
fun(Opts) ->
RootType = "org.apache.avro.test",
Encoder = avro:make_encoder(Lkup, Opts),
Decoder = avro:make_decoder(Lkup, Opts),
Encoded = Encoder(RootType, Input),
Decoded = Decoder(RootType, Encoded),
?assertEqual(Expect, Decoded)
end,
TestFun([{encoding, avro_binary}]),
TestFun([{encoding, avro_json}]),
ok.

default_values_with_map_type_test() ->
File = filename:join(priv_dir(), "test.avsc"),
{ok, JSON} = file:read_file(File),
Expand Down

0 comments on commit ebdee67

Please sign in to comment.