From b94a57d1bdc25fcd632938426641f814ef2a89b7 Mon Sep 17 00:00:00 2001 From: Zach Daniel Date: Thu, 8 Dec 2022 01:49:05 -0500 Subject: [PATCH] improvement: add `:struct` (`Ash.Type.struct`) type --- lib/ash/type/struct.ex | 48 ++++++++++++++++++++++++++++++++++++++++++ lib/ash/type/type.ex | 1 + mix.exs | 2 +- 3 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 lib/ash/type/struct.ex diff --git a/lib/ash/type/struct.ex b/lib/ash/type/struct.ex new file mode 100644 index 00000000..54ccded9 --- /dev/null +++ b/lib/ash/type/struct.ex @@ -0,0 +1,48 @@ +defmodule Ash.Type.Struct do + @moduledoc """ + Represents a struct. + + This cannot be loaded from a database, it can only be used to cast input. + + Use the `instance_of` constraint to specify that it must be an instance of a specific struct. + """ + use Ash.Type + + @constraints [ + instance_of: [ + type: :atom, + doc: "The module the struct should be an instance of", + default: false + ] + ] + + @impl true + def constraints, do: @constraints + + @impl true + def storage_type, do: :map + + @impl true + def cast_input(nil, _), do: {:ok, nil} + + def cast_input(%struct{} = value, constraints) do + case constraints[:instance_of] do + nil -> + {:ok, value} + + ^struct -> + {:ok, value} + + _ -> + :error + end + end + + def cast_input(_, _), do: :error + + @impl true + def cast_stored(_, _), do: :error + + @impl true + def dump_to_native(_, _), do: :error +end diff --git a/lib/ash/type/type.ex b/lib/ash/type/type.ex index 0017bdfe..a42de652 100644 --- a/lib/ash/type/type.ex +++ b/lib/ash/type/type.ex @@ -25,6 +25,7 @@ defmodule Ash.Type do duration_name: Ash.Type.DurationName, function: Ash.Type.Function, boolean: Ash.Type.Boolean, + struct: Ash.Type.Struct, uuid: Ash.Type.UUID, binary: Ash.Type.Binary, date: Ash.Type.Date, diff --git a/mix.exs b/mix.exs index f451f751..b0232973 100644 --- a/mix.exs +++ b/mix.exs @@ -220,7 +220,7 @@ defmodule Ash.MixProject do # Run "mix help deps" to learn about dependencies. defp deps do [ - {:spark, "~> 0.2 and >= 0.2.18"}, + {:spark, "~> 0.2.18"}, {:ecto, "~> 3.7"}, {:ets, "~> 0.8.0"}, {:decimal, "~> 2.0"},