vt-elixir / ja_serializer

JSONAPI.org Serialization in Elixir.
Other
640 stars 148 forks source link

[Updated] formatting for nested attributes #302

Closed broodfusion closed 5 years ago

broodfusion commented 5 years ago

Hi @beerlington, I submitted a new PR here. Continuation from https://github.com/vt-elixir/ja_serializer/pull/295

broodfusion commented 5 years ago

FYI, could probably add this in the readme file:

To serialize nested attributes in a Phoenix app, include this anywhere:

defimpl JaSerializer.Formatter,
  for: [JaSerializer.Builder.Attribute] do
  alias JaSerializer.Formatter.Utils

  def format(%{value: value, key: key}) when is_map(value) or is_list(value) do
    values = Utils.deep_format_keys(value)
    {Utils.format_key(key), JaSerializer.Formatter.format(values)}
  end

  def format(attr) do
    {Utils.format_key(attr.key), JaSerializer.Formatter.format(attr.value)}
  end
end

Couldn't have this in attribute.ex because it would break the tests in attributes_test.ex for "allows overriding for struct formatting" and "map formatter can be changed".

Thanks!