morfertaw

morfertaw

Serializing Ash Structs with Jason

So I am using live_svelte which lets you use svelte in your live_views. You pass in the props to the svelte component in a h_sigil and live_svelte serializer them using Jason. Is it possible to derive the encoder for ash resource structs?

Marked As Solved

zachdaniel

zachdaniel

Creator of Ash

I think I’d actually suggest not using a protocol-based encoder, primarily because with Ash resources you can have calculations/aggregates/metadata that you may want to display along with the resource. For instance, if you wanted to show related data, or if you wanted to show computed properties, you might want something like this:

def encode(resources, opts \\ []) do
  Jason.encode!(sanitize(resources, opts))
end

defp sanitize(records, opts) when is_list(resources) do
  Enum.map(records, &sanitize(&1, opts))
end

defp sanitize(%resource{} = record, opts) do
  if Ash.Resource.Info.resource?(resource) do
    fields = opts[:fields] || public_attributes(record)

    Map.new(fields, fn
      {field, further} ->
        {field, sanitize(Map.get(record, field), further)} 
      field -> 
        {field, sanitize(Map.get(record, field), [])} 
      end)
  else
    record
  end
end

defp sanitize(value, _), do: value

defp public_attributes(%resource{}), do: resource |> Ash.Resource.Info.public_attributes() |> Enum.map(&(&1.name))

Something like the above would let you call encode(record, fields: [:field1, :field2, relationship: [fields: [:field3]]).

This lets you load data and serialize it, i.e

MyResource
|> Ash.Query.load([:field1, :field2, relationship: [:field3]])
|> MyApi.read!()
|> Encoder.encode(fields: [:field1, :field2, relationship: [fields: [:field3]])

Also Liked

vonagam

vonagam

Alternative solution for those who stumble upon this thread:

Had the same use case with live_svelte and decided to go with more automatic approach by writing an Ash extension that defines customizable Jason implementation for a resource based on its fields - ash_jason.

To get some reasonable default behavior just include AshJason.Extension into extensions in use Ash.Resource call. To customize use optional jason section.

It is also possible to write your own extension using ash_jason as a reference point - the library is small, just around hundred lines between two files.

13
Post #5
morfertaw

morfertaw

Wow. This is great. I’m guessing the names are a little wrong. They should be.

def encode(records, opts \\ []) do
  Jason.encode!(sanitize(records, opts))
end

defp sanitize(records, opts) when is_list(records) do
  Enum.map(records, &sanitize(&1, opts))
end

Cheers!

Where Next?

Popular in Questions Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
earth10
Hi, I’m just starting to build a side-project with Elixir and Phoenix and doing some basic test with Elixir alone. What strikes me is th...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New

Other popular topics Top

ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New

We're in Beta

About us Mission Statement