acalejos / flint

Declarative Ecto embedded schemas for data validation, coercion, and manipulation.
MIT License
104 stars 3 forks source link

Provide a construction API returns a tuple #13

Open fishtreesugar opened 1 week ago

fishtreesugar commented 1 week ago

Currently, there are two APIs for constructing a struct: new and new!. The new function ignores changeset errors and returns the struct regardless, while new! raises an ArgumentError when there are changeset errors. In Elixir, using with for error handling is common:

with {:ok, payload} <- Foo.parse(raw_input),
     :ok, _result} <- do_sth(payload) do
  :ok
end

For cases with no changeset errors, parse will return {:ok, struct}; otherwise, it will return {:error, changeset}. Of course, the name of the API could be discussed further. To align with the "Parse, don't validate" slogan, it would be beneficial if flint provided such an API.

acalejos commented 1 week ago

I definitely contemplated this. It should probably change to new outputting a tuple, and new! raising. Then maybe have an option in new like :ignore_errors. Thoughts?

fishtreesugar commented 1 week ago

It should probably change to new outputting a tuple, and new! raising.

Yes, I think it should be closer to the convection of Elixir's stdlib, e.g. fetch/2 v.s. fetch!/2

Then maybe have an option in new like :ignore_errors. Thoughts?

In my opinion, it shouldn't allow an easy way to skip the error. 😂

FWIW, thank you for your quick response!