nikokozak

nikokozak

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?

Showing Posts 1 to 4

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?

nikokozak

nikokozak OP

Thanks @dimitarvp - you’re right about the data consistency guarantees, it just felt a bit hacked together the first time I tried it (particularly the act of pulling from the encoded :__struct__ in order to create a new instance for casting). Having said that, it’s also pretty cool - thank you for confirming it’s a sane strategy.

The data itself is sanitized and passed through our own changesets before insertion and encoding, so there’s relatively little risk of malformed inputs.

Just as a side note, the only way I’ve been able to persist the :__struct__ field with Jason is by explicitly mentioning it in the only: option of the derive, like so:

@derive {Jason.Encoder, only: [:__struct__, etc.]} 
embedded_schema do...

Is there any other way to force the encoding of “hidden” fields without necessarily implementing Jason from scratch?

Thanks again.

dimitarvp

dimitarvp

There’s two sides to this:

  1. You might not be experienced enough with the technology today so these things aren’t coming naturally to you… yet.
  2. You might be coming from other technologies where the frameworks are more automatic and hands-off and the cognitive dissonance of “do I have to do it myself?!” might be getting to you.

Both are possible to overcome. :+1:

None that I am aware of but that solution is quite fine – you are opting out of a sane default behaviour and saying “I know what I am doing, please serialize these fields exactly as I say”.

nikokozak

nikokozak OP

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

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews