phcurado / parameter

Schema creation, validation, serialization and deserialization for input data
https://hexdocs.pm/parameter
Apache License 2.0
56 stars 1 forks source link

Parameter.load implicitly casts values with no user control #66

Open LeartS opened 1 month ago

LeartS commented 1 month ago

Parameter.load defaults to casting values and there doesn't seem to be a way to disable that behaviour.

Simple example to reproduce

  defmodule UserPayload do
    use Parameter.Schema

    param do
      field :user_id, :string
    end
  end
Parameter.load(UserPayload, %{"user_id" => false})
# {:ok, %{user_id: "false"}}

I would like to get an error when I get an invalid user payload, not an implicit cast. I'd argue that should be the default behaviour, but I'd settle for an extra option in Paramter.load/3 to explicitly disable it, e.g.

Parameter.load(UserPayload, %{"user_id" => false}, implicit_casting: false)
# {:error, %{user_id: "invalid string type"}}

I know I could use validate first and then load, but that it's just ugly, redundant the goes against the functional Parse, don't validate best practice.

phcurado commented 3 weeks ago

Hi @LeartS, the library does not perform strict parsing by design, as an example you can check the boolean parser where you will see that even strings or integers like "1" or 0 will be valid boolean values for casting. The reason for that is because this lib was designed for parsing values from external data, where this data may be unknown, returning unexpected values. Because of this, Parameter does it's best to parse the values by having this non strict behaviour. For strict validation I created the validate function to fit this purpose.