Skip to content

Optional maps get created when raw_value == nil #15

@bmurphy23

Description

@bmurphy23

If a map attribute is marked as optional, and the incoming params do not have that data, then the struct that Speck outputs will have an empty(-ish) map for that attribute. Here's a barebones example:

struct MyNamespace.FooData

name "foo_data"

attribute :name, :string
attribute :status, :atom, values: [:ok, :not_okay]

attribute :data, optional: true do
  attribute :timestamp, :datetime
  attribute [:values] do
    attribute :value_1, :integer
    attribute :value_2, :string
  end
end

Then, in iex:

json = """
{
  "name": "foo",
  "status": "ok"
}
"""
message = Jason.decode!(json)

Speck.validate(MyNamespace.FooData, message)

If you run this, you'll get this returned:

{
  :ok,
  %MyNamespace.FooData{
    name: "foo",
    status: :ok,
    data: %{
      values: []
    }
  }
}

There are two interesting things I'm seeing here:

  • :data exists at all in the returned struct.
  • :values is included in the map, but :timestamp isn't.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions