56 lines
1.4 KiB
Elixir
56 lines
1.4 KiB
Elixir
defmodule Mv.Membership.CustomFieldLookup do
|
|
@moduledoc """
|
|
Shared helper for loading custom fields by ID.
|
|
"""
|
|
|
|
alias Mv.Constants
|
|
alias Mv.Membership
|
|
|
|
@spec fetch_map_by_ids([String.t()], keyword()) :: map()
|
|
def fetch_map_by_ids(field_ids, opts \\ []) when is_list(field_ids) do
|
|
member_field_strings = Constants.member_fields() |> Enum.map(&Atom.to_string/1)
|
|
|
|
custom_field_ids =
|
|
field_ids
|
|
|> Enum.uniq()
|
|
|> Enum.reject(&(&1 in member_field_strings))
|
|
|
|
if custom_field_ids == [] do
|
|
%{}
|
|
else
|
|
select = Keyword.get(opts, :select, [:id, :name, :value_type])
|
|
|
|
query =
|
|
Membership.CustomField
|
|
|> Ash.Query.select(select)
|
|
|
|
read_opts =
|
|
[domain: Membership]
|
|
|> maybe_put_actor(opts)
|
|
|> maybe_put_authorize(opts)
|
|
|
|
case Ash.read(query, read_opts) do
|
|
{:ok, fields} ->
|
|
allowed_ids = MapSet.new(custom_field_ids)
|
|
fields |> Enum.filter(&MapSet.member?(allowed_ids, &1.id)) |> Map.new(&{&1.id, &1})
|
|
|
|
{:error, _} ->
|
|
%{}
|
|
end
|
|
end
|
|
end
|
|
|
|
defp maybe_put_actor(opts, read_opts) do
|
|
case Keyword.fetch(read_opts, :actor) do
|
|
{:ok, actor} -> Keyword.put(opts, :actor, actor)
|
|
:error -> opts
|
|
end
|
|
end
|
|
|
|
defp maybe_put_authorize(opts, read_opts) do
|
|
case Keyword.fetch(read_opts, :authorize?) do
|
|
{:ok, authorize?} -> Keyword.put(opts, :authorize?, authorize?)
|
|
:error -> opts
|
|
end
|
|
end
|
|
end
|