Ash FrameworkAF
Ash Framework2mo ago
7 replies
zackattackz

Untagged union type argument containing custom types

Howdy :)

I was trying to make an argument for a create action of type :union, which would either be a singleton of some value of a custom type, or an array of values of that custom type.

Snippet of the action:
create :enqueue do
  accept @mail_create_accepts
  argument :to, :union,
    constraints: [
      types: [
        mailbox: [
          type: PetRockRental.Types.Mailbox,
        ],
        mailboxes: [
          type: {:array, PetRockRental.Types.Mailbox},
        ]
      ]
    ]
  change transition_state(:queued)
end


and the PetRockRental.Types.Mailbox:
defmodule PetRockRental.Types.Mailbox do
  use Ash.Type.NewType,
    subtype_of: :tuple,
    constraints: [
      fields: [
        display: [type: :string],
        email:   [type: :string]
      ]
    ]
end


The idea is the user of this action should be able to pass in either a single tuple e.g (via a code interface) PetRockRental.Mail.enqueue_mail(%{to: {"Jane Doe", "jane@example.com"}}) Or a list of tuples PetRockRental.Mail.enqueue_mail(%{to: [{"Jane Doe", "jane@example.com"}, {"John Doe", "john@example.com"}]})

Under the hood this argument will be converted to be stored as an :array whether it's a single item or not, but I wanted to provide the ability to call the action with a singleton or an array for convenience rather than always needing to pass a list.
Was this page helpful?