drops
drops copied to clipboard
Support to declare that a key needs to conform with the given Struct
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
Thanks for reporting the issue! This will be supported eventually 😄
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.