diff --git a/lib/typed/serializer.rb b/lib/typed/serializer.rb index c370edb..8d75363 100644 --- a/lib/typed/serializer.rb +++ b/lib/typed/serializer.rb @@ -38,6 +38,8 @@ def deserialize_from_creation_params(creation_params) if value.nil? && !field.default.nil? Success.new(Validations::ValidatedValue.new(name: field.name, value: field.default)) + elsif !field.required && (value.nil? || value == "") + Success.new(Validations::ValidatedValue.new(name: field.name, value: nil)) elsif value.nil? || field.works_with?(value) field.validate(value) elsif !coercer.nil? diff --git a/test/typed/hash_serializer_test.rb b/test/typed/hash_serializer_test.rb index ab1dc8b..568e880 100644 --- a/test/typed/hash_serializer_test.rb +++ b/test/typed/hash_serializer_test.rb @@ -123,6 +123,13 @@ def test_with_boolean_string_true_it_can_deserialize assert_payload(DC_CITY, result) end + def test_with_empty_string_for_nilable_it_can_deserialize + result = Typed::HashSerializer.new(schema: Typed::Schema.from_struct(Job)).deserialize({title: "Software Developer", salary: {cents: 9000000, currency: "USD"}, start_date: ""}) + + assert_success(result) + assert_payload(DEVELOPER_JOB, result) + end + def test_with_array_it_can_deserialize result = Typed::HashSerializer.new(schema: Typed::Schema.from_struct(Country)).deserialize({name: "US", cities: [NEW_YORK_CITY, DC_CITY], national_items: {bird: "bald eagle", anthem: "The Star-Spangled Banner"}}) diff --git a/test/typed/json_serializer_test.rb b/test/typed/json_serializer_test.rb index 538bf24..9c51e21 100644 --- a/test/typed/json_serializer_test.rb +++ b/test/typed/json_serializer_test.rb @@ -74,6 +74,13 @@ def test_with_boolean_string_true_it_can_deserialize assert_payload(DC_CITY, result) end + def test_with_empty_string_for_nilable_it_can_deserialize + result = Typed::JSONSerializer.new(schema: Typed::Schema.from_struct(Job)).deserialize('{"title":"Software Developer","salary":{"cents":9000000,"currency":"USD"},"start_date":""}') + + assert_success(result) + assert_payload(DEVELOPER_JOB, result) + end + def test_with_array_it_can_deep_deserialize result = Typed::JSONSerializer.new(schema: Typed::Schema.from_struct(Country)).deserialize('{"name":"US","cities":[{"name":"New York","capital":false},{"name":"DC","capital":true}],"national_items":{"bird":"bald eagle","anthem":"The Star-Spangled Banner"}}')