Skip to content

Commit

Permalink
feat!: treat empty string as a nil value in deser
Browse files Browse the repository at this point in the history
  • Loading branch information
maxveldink committed Dec 10, 2024
1 parent ca55923 commit 3162498
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 0 deletions.
2 changes: 2 additions & 0 deletions lib/typed/serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down
7 changes: 7 additions & 0 deletions test/typed/hash_serializer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"}})

Expand Down
7 changes: 7 additions & 0 deletions test/typed/json_serializer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"}}')

Expand Down

0 comments on commit 3162498

Please sign in to comment.