refactor: use Map.update! for state updates

This commit is contained in:
Roman 2023-06-06 17:01:17 -04:00
parent d314398500
commit da0f899eac

View file

@ -111,6 +111,7 @@ defmodule Sergei.Player do
{:noreply, state} {:noreply, state}
end end
# Play
@impl true @impl true
def handle_call({:play, guild_id, channel_id, url}, _from, state) do def handle_call({:play, guild_id, channel_id, url}, _from, state) do
res = play_music(guild_id, channel_id, url) res = play_music(guild_id, channel_id, url)
@ -125,54 +126,40 @@ defmodule Sergei.Player do
{:reply, res, state} {:reply, res, state}
end end
# Queue
@impl true @impl true
def handle_call({:queue, guild_id, url}, _from, state) do def handle_call({:queue, guild_id, url}, _from, state) do
%{queue: queue} = instance = Map.fetch!(state, guild_id) %{queue: queue} = Map.fetch!(state, guild_id)
{ {
:reply, :reply,
:ok, :ok,
Map.put( Map.update!(
state, state,
guild_id, guild_id,
%{instance | queue: :queue.in(url, queue)} &%{&1 | queue: :queue.in(url, queue)}
) )
} }
end end
# Guard: Ensure Sergei is playing something in the guild
@impl true @impl true
def handle_call({_, guild_id}, _from, state) when not is_map_key(state, guild_id) do def handle_call({_, guild_id}, _from, state) when not is_map_key(state, guild_id) do
{:reply, :not_playing, state} {:reply, :not_playing, state}
end end
# Pause
@impl true @impl true
def handle_call({:pause, guild_id}, _from, state) do def handle_call({:pause, guild_id}, _from, state) do
%{url: url, queue: queue} = Map.fetch!(state, guild_id)
Voice.pause(guild_id) Voice.pause(guild_id)
{:reply, :ok, Map.update!(state, guild_id, &%{&1 | paused: true})}
state =
Map.put(state, guild_id, %{
url: url,
paused: true,
queue: queue
})
{:reply, :ok, state}
end end
# Resume
@impl true @impl true
def handle_call({:resume, guild_id}, _from, state) do def handle_call({:resume, guild_id}, _from, state) do
%{url: url, queue: queue} = Map.fetch!(state, guild_id)
Voice.resume(guild_id) Voice.resume(guild_id)
{:reply, :ok, Map.update!(state, guild_id, &%{&1 | paused: false})}
state =
Map.put(state, guild_id, %{
url: url,
paused: false,
queue: queue
})
{:reply, :ok, state}
end end
@impl true @impl true