Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Struct fields are not enforced #5

Open
xxdavid opened this issue Feb 6, 2023 · 2 comments
Open

Struct fields are not enforced #5

xxdavid opened this issue Feb 6, 2023 · 2 comments

Comments

@xxdavid
Copy link

xxdavid commented Feb 6, 2023

Hi, thanks for this library. 🙂

It works well but it does not enforce fields that are declared in the struct to be enforced.

Imagine this struct:

defmodule Person do
  @enforce_keys [:name]
  defstruct name: nil,
            age: nil,
            happy?: true,
            phone: nil

  @type t() :: %__MODULE__{
          name: String.t(),
          age: non_neg_integer() | nil,
          happy?: boolean(),
          phone: String.t() | nil
        }
end

Now if you evaluate

data = %{"age" => 42, "happy?" => true, "phone" => "(206) 342-8631"}
Forma.parse(data, Person)

you get

{:ok, %Person{age: 42, happy?: true, name: nil, phone: "(206) 342-8631"}}

Notice that the call was successful and :name is set to nil even though it is in @enforced_keys and its type is not nullable.

Instead, if you evaluate %Person{age: 42, happy?: true, phone: "(206) 342-8631"}, you get this error: (ArgumentError) the following keys must also be given when building struct Person: [:name].

I think Forma should enforce :name being present in data as well. What do you think?

I think it could be achieved by changing the struct clause for Forma.Parser.parse!/3 from this:

  def parse!(input, parsers, {:struct, name, fields}) do
    case input do
      input when is_map(input) -> map_exact_fields!(input, parsers, struct(name), fields)
      _ -> raise "not a map #{inspect(input)}"
    end
  end

to something like this:

  def parse!(input, parsers, {:struct, name, fields}) do
    case input do
      input when is_map(input) -> map_exact_fields!(input, parsers, %{}, fields) |> then(&struct!(name, &1))
      _ -> raise "not a map #{inspect(input)}"
    end
  end
@frekw
Copy link
Member

frekw commented Feb 8, 2023

Hi @xxdavid!

I agree that would be nice indeed.

We're not really using this library (nor Elixir) anymore so it's unlikely that I'll have time to fix it, but PRs and contributions are very welcome! 🙏

@xxdavid
Copy link
Author

xxdavid commented Feb 8, 2023

Hi @frekw, thanks for replying even though you aren't interested in this library anymore (unfortunately, such behaviour is not very common).

If I find some time, I might come up with a PR. 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants