-
Notifications
You must be signed in to change notification settings - Fork 0
/
people_channel.ex
67 lines (58 loc) · 1.82 KB
/
people_channel.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
defmodule SillyCrmWeb.PeopleChannel do
@moduledoc false
use LiveState.Channel, web_module: SillyCrmWeb
alias SillyCrm.People
@impl true
def init(_channel, _params, _socket) do
{:ok, %{people: People.list_people(), errors: %{}, editing: false, person: %People.Person{}}}
end
@impl true
def handle_event("add-person", _attrs, state) do
{:noreply,
state
|> Map.put(:editing, true)
|> Map.put(:person, %People.Person{})
|> Map.put(:errors, %{})}
end
@impl true
def handle_event("edit-person", %{"id" => person_id}, state) do
{:noreply,
state
|> Map.put(:editing, true)
|> Map.put(:person, People.get_person!(person_id))
|> Map.put(:errors, %{})}
end
def handle_event("save-person", attrs, %{person: %{id: person_id} = person} = state)
when not is_nil(person_id) do
with person <- People.get_person!(person_id),
{:ok, saved_person} <- People.update_person(person, attrs) do
{:noreply,
%{
people: People.list_people(),
person: saved_person,
editing: false
}}
else
{:error, changeset} ->
{:noreply,
Map.put(state, :errors, format_errors(changeset))
|> Map.put(:person, Map.merge(person, attrs))}
end
end
def handle_event("save-person", person, state) do
case People.create_person(person) do
{:ok, saved_person} ->
{:noreply,
%{
people: People.list_people(),
person: saved_person,
editing: false
}}
{:error, changeset} ->
{:noreply,
state |> Map.put(:errors, format_errors(changeset)) |> Map.put(:person, person)}
end
end
defp format_errors(%Ecto.Changeset{errors: errors}),
do: errors |> Enum.map(fn {field, {message, _}} -> {field, message} end) |> Enum.into(%{})
end