|
| 1 | +# SPDX-FileCopyrightText: 2025 diffo contributors <https://github.com/diffo-dev/diffo/graphs.contributors> |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +defmodule Diffo.Provider.Changes.Define do |
| 6 | + @moduledoc """ |
| 7 | + After-action change for the standard `:define` pattern. |
| 8 | +
|
| 9 | + Applies `characteristic_value_updates` to the instance's declared typed and |
| 10 | + dynamic characteristics (`Characteristic.update_all/3`) and to its declared |
| 11 | + pools (`Pool.update_pools/3`), then reloads the result via the resource's |
| 12 | + primary `:read` action. |
| 13 | +
|
| 14 | + ## Usage |
| 15 | +
|
| 16 | + update :define do |
| 17 | + argument :characteristic_value_updates, {:array, :term} |
| 18 | + change Diffo.Provider.Changes.Define |
| 19 | + end |
| 20 | +
|
| 21 | + This replaces the hand-written `after_action` block that threads |
| 22 | + `characteristics()`, `pools()`, `Characteristic.update_all/3` and |
| 23 | + `Pool.update_pools/3` together on every consumer. |
| 24 | + """ |
| 25 | + use Ash.Resource.Change |
| 26 | + |
| 27 | + require Ash.Query |
| 28 | + |
| 29 | + alias Diffo.Provider.Extension.Characteristic |
| 30 | + alias Diffo.Provider.Extension.Pool |
| 31 | + |
| 32 | + @impl true |
| 33 | + def change(changeset, _opts, _context) do |
| 34 | + Ash.Changeset.after_action(changeset, fn changeset, result -> |
| 35 | + module = changeset.resource |
| 36 | + |
| 37 | + with {:ok, result} <- Ash.load(result, [:characteristics]), |
| 38 | + {:ok, result} <- Characteristic.update_all(result, changeset, module.characteristics()), |
| 39 | + {:ok, result} <- Pool.update_pools(result, changeset, module.pools()) do |
| 40 | + id = result.id |
| 41 | + |
| 42 | + module |
| 43 | + |> Ash.Query.for_read(:read) |
| 44 | + |> Ash.Query.filter(id == ^id) |
| 45 | + |> Ash.read_one() |
| 46 | + end |
| 47 | + end) |
| 48 | + end |
| 49 | +end |
0 commit comments