vt-elixir / ja_serializer

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

How to get a custom attribute value formatter to work properly. #305

Closed brennan-karrer closed 5 years ago

brennan-karrer commented 5 years ago

I'm having an issue trying to get a custom attribute formatter working for the structs in my application. Per the documentation, I should be able to do so via the following:

defimpl JaSerializer.Formatter, for: [MyStruct] do
  def format(struct), do: struct
end

Here's an example of how I'm trying to implement the Formatter protocol for my struct:

defmodule MyApp.Model.Call do
  ...
  @derive [ExAws.Dynamo.Encodable]
  defstruct accept_at: "",
            audio_url: "",
            destination_category: "",
            destination_number: "0000000000",
            duration: ""
  ...
end
defimpl JaSerializer.Formatter, for: [MyApp.Model.Call] 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

The only thing that I could think of is maybe the Formatter module doesn't like me trying to pass a struct derived from my Dynamo module? Neither of these functions ever get hit so I'm a bit confused.

Any help would be much appreciated.

beerlington commented 5 years ago

@brennan-karrer it seems like what you have should work, though I can't confirm whether using @derive is the culprit. Are you able to confirm that JaSerializer uses the formatter if you remove the @derive line?

brennan-karrer commented 5 years ago

@beerlington I haven't tested it out without utilizing the @derive as we need that line in order to map data from Dynamo to the appropriate structure. I'll have to create a dummy application and test out if it works without the @derive annotation.

beerlington commented 5 years ago

@brennan-karrer were you able to resolve this?

beerlington commented 5 years ago

Closing since there hasn't been a response