|
| 1 | +defmodule BookStore.Books.BookProcess do |
| 2 | + use GenServer, restart: :transient |
| 3 | + |
| 4 | + require Logger |
| 5 | + |
| 6 | + alias BookStore.Repo |
| 7 | + alias BookStore.Books.Book |
| 8 | + alias Ecto.Changeset |
| 9 | + |
| 10 | + def start_link(%Book{} = book) do |
| 11 | + GenServer.start_link(__MODULE__, book, |
| 12 | + name: {:via, Registry, {BookStore.BookRegistry, book.id}} |
| 13 | + ) |
| 14 | + end |
| 15 | + |
| 16 | + @impl true |
| 17 | + def init(%Book{} = state) do |
| 18 | + {:ok, state} |
| 19 | + end |
| 20 | + |
| 21 | + @impl true |
| 22 | + def handle_call(:read, _from, %Book{} = state) do |
| 23 | + {:reply, state, state} |
| 24 | + end |
| 25 | + |
| 26 | + @impl true |
| 27 | + def handle_call({:update, attrs}, _from, %Book{} = state) do |
| 28 | + state |
| 29 | + |> update_book(attrs) |
| 30 | + |> case do |
| 31 | + {:ok, %Book{} = updated_book} -> |
| 32 | + {:reply, updated_book, updated_book, {:continue, :persist_book_changes}} |
| 33 | + |
| 34 | + error -> |
| 35 | + {:reply, error, state} |
| 36 | + end |
| 37 | + end |
| 38 | + |
| 39 | + @impl true |
| 40 | + def handle_call(:order_copy, _from, %Book{quantity: 0} = state) do |
| 41 | + {:reply, :no_copies_available, state} |
| 42 | + end |
| 43 | + |
| 44 | + @impl true |
| 45 | + def handle_call(:order_copy, _from, %Book{quantity: quantity} = state) do |
| 46 | + state |
| 47 | + |> update_book(%{quantity: quantity - 1}) |
| 48 | + |> case do |
| 49 | + {%Book{} = updated_book, changeset} -> |
| 50 | + {:reply, :ok, updated_book, {:continue, {:persist_book_changes, changeset}}} |
| 51 | + |
| 52 | + error -> |
| 53 | + {:reply, error, state} |
| 54 | + end |
| 55 | + end |
| 56 | + |
| 57 | + @impl true |
| 58 | + def handle_continue({:persist_book_changes, changeset}, state) do |
| 59 | + Repo.update(changeset) |
| 60 | + |
| 61 | + {:noreply, state} |
| 62 | + end |
| 63 | + |
| 64 | + defp update_book(book, attrs) do |
| 65 | + book |
| 66 | + |> Book.changeset(attrs) |
| 67 | + |> case do |
| 68 | + %Changeset{valid?: true} = changeset -> |
| 69 | + updated_book = Changeset.apply_changes(changeset) |
| 70 | + {updated_book, changeset} |
| 71 | + |
| 72 | + error_changeset -> |
| 73 | + {:error, error_changeset} |
| 74 | + end |
| 75 | + end |
| 76 | +end |
0 commit comments