nikokozak

nikokozak

Re-casting json-encoded structs gracefully

Hi all - I might have dug my own grave by going down this path, but now I’m just curious… What is the best way to re-cast data after decoding a struct that has been encoded as json in order to be persisted? I’m working with embedded_schemas nested in a map that gets encoded when persisted via Ecto/PSQL. A very simplified version looks like this:

defmodule App.InnerSchema do

  embedded_schema do
    field :a_field, :string
    field :date_scheduled, :utc_datetime
  end

end

defmodule App.ParentSchema do

  schema "parents" do

    # a series of App.InnerSchema-like structs, all slightly different,
    # get stored here like so:
    # %{ plugin_1: %InnerSchema{}, plugin_2: %ADifferentInnerSchema{}, etc.. }
    field :stored_here, :map

  end

end

I thought about defining an Ecto.Type for :embedded_here, but the problem I have is that per the nature of the program, I can never be entirely sure what embedded_structs have been included in the encoded map, and while I could check fields against a list of probable structs when loading, it doesn’t seem graceful. I also tried forcing Jason.Encoder to encode the __struct__ field from the original InnerSchema in order to rescue it when decoding: the idea being, I could then cast the values I extract from the decoded json map using Ecto.Changeset.cast(the_decoded_json, apply(S.to_e_A(the_decoded_struct_field), :__struct__, []), ~w(the_fields), _opts), as per this old thread but cast keeps giving me an error saying it expects a :map instead of the %InnerSchema{}.

This might be a bit convoluted all in all, but ultimately all I want is a way to easily cast/decode each field’s type (namely for more complex stuff, like datetimes and custom Types), according to the struct that field is nested in after Jason encoding. Now that I’m typing it out, I realize it’s also about rescuing as much as possible from the json encoding (i know, i know). Any nice ways to do this?

Marked As Solved

dimitarvp

dimitarvp

Making your own Ecto.Types and just recursively cast – which happens automatically when you declare your schemata well – I found is the best way, both in professional and hobby projects.

What’s troubling you? Yeah it’s a bit manual… the first time. You gain stronger data consistency guarantees though.

Also, where does the data come from? Should there be a tolerance for malformed inputs?

Also Liked

nikokozak

nikokozak

Yep - I’ve always avoided playing with the internals of data in other languages. I’m loving that I can do that with Elixir (responsibly).

Great, makes sense the Jason behaviour would be specified like that.

Again, thank you for your help @dimitarvp

Last Post!

nikokozak

nikokozak

Yep - I’ve always avoided playing with the internals of data in other languages. I’m loving that I can do that with Elixir (responsibly).

Great, makes sense the Jason behaviour would be specified like that.

Again, thank you for your help @dimitarvp

Where Next?

Popular in Questions Top

New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
marius95
Hello everyone, I try to use an Javascript Event Handler in my root.html.leex file. Therefore I created a function in the app.js file: ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
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 31525 112
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
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
New

We're in Beta

About us Mission Statement