drops icon indicating copy to clipboard operation
drops copied to clipboard

Support to declare that a key needs to conform with the given Struct

Open Exadra37 opened this issue 1 year ago • 1 comments

I want to be able to declare the following contract required(:key) => %SomeStruct{} on a drop.

It doesn't seem possible to achieve this, even when using custom types, or am I missing something?

Full example:

defmodule MyApp.APIContract do
    use Drops.Contract

    alias MyApp.WhateverStruct

    @enforce_keys [:context, :action]

    defstruct @enforce_keys

    schema do
      %{
        required(:context) => %WhateverStruct{},
        required(:action) => string(:filled?),
      }
    end

    def new(attrs) when is_map(attrs) do
      case conform(attrs) do
        {:ok, attrs} ->
          struct(__MODULE__, attrs)

        error ->
          error
      end
    end
  end

Exadra37 avatar May 31 '24 11:05 Exadra37

Thanks for reporting the issue! This will be supported eventually 😄

solnic avatar Jun 02 '24 05:06 solnic

Maybe the easiest way would be to add a predicate is_struct? to check if a map is of a struct of a given type?. So something like

schema do
  required(:context) => map(is_struct?: WhateverStruct)
end

If that sounds OK, I can write up a quick PR.

uhoreg avatar Oct 10 '25 02:10 uhoreg