From 6a2bb30d1d0ecf025c6154d90f7f737af0aedcb4 Mon Sep 17 00:00:00 2001 From: Zach Daniel Date: Thu, 14 Sep 2023 16:52:08 -0400 Subject: [PATCH] improvement: add `allow_nil?` to generic actions, defaults to false --- lib/ash/action_input.ex | 8 ++++++-- lib/ash/actions/action.ex | 9 +++++++++ lib/ash/resource/actions/action/action.ex | 9 +++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lib/ash/action_input.ex b/lib/ash/action_input.ex index fdb910f9..e1254e11 100644 --- a/lib/ash/action_input.ex +++ b/lib/ash/action_input.ex @@ -19,12 +19,15 @@ defmodule Ash.ActionInput do @type t :: %__MODULE__{ arguments: map(), params: map(), - action: Ash.Resource.Actions.Action.t(), + action: Ash.Resource.Actions.Action.t() | nil, resource: Ash.Resource.t(), context: map(), api: Ash.Api.t(), valid?: boolean() } + def new(resource, api \\ nil) do + %__MODULE__{resource: resource, api: api} + end @doc """ Creates a new input for a generic action @@ -43,7 +46,8 @@ defmodule Ash.ActionInput do %__MODULE__{resource: resource, action: action} input -> - input + action = Ash.Resource.Info.action(input.resource, action) + %{input | action: action} end {input, _opts} = Ash.Actions.Helpers.add_process_context(input.api, input, opts) diff --git a/lib/ash/actions/action.ex b/lib/ash/actions/action.ex index 3bfaa534..f8485cdc 100644 --- a/lib/ash/actions/action.ex +++ b/lib/ash/actions/action.ex @@ -120,6 +120,15 @@ defmodule Ash.Actions.Action do {:error, error} -> {:error, error} + + other -> + raise """ + Invalid return from generic action #{input.resource}.#{input.action.name}. + + Expected {:ok, result} or {:error, error}, got: + + #{inspect(other)} + """ end {:error, error} -> diff --git a/lib/ash/resource/actions/action/action.ex b/lib/ash/resource/actions/action/action.ex index 79ccece6..5abaa707 100644 --- a/lib/ash/resource/actions/action/action.ex +++ b/lib/ash/resource/actions/action/action.ex @@ -9,6 +9,7 @@ defmodule Ash.Resource.Actions.Action do constraints: [], touches_resources: [], arguments: [], + allow_nil?: false, transaction?: false, primary?: false, type: :action @@ -19,6 +20,7 @@ defmodule Ash.Resource.Actions.Action do name: atom, description: String.t() | nil, arguments: [Ash.Resource.Actions.Argument.t()], + allow_nil?: boolean, touches_resources: [Ash.Resource.t()], constraints: Keyword.t(), run: {module, Keyword.t()}, @@ -41,6 +43,13 @@ defmodule Ash.Resource.Actions.Action do Constraints for the return type. See the [constriants topic](/documentation/topics/constraints.md) for more. """ ], + allow_nil?: [ + type: :boolean, + default: false, + doc: """ + Wether or not the action can return nil. Unlike attributes & arguments, this defaults to `false`. + """ + ], run: [ type: {:spark_function_behaviour, Ash.Resource.Actions.Implementation,