A last.fm clone written in Elixir
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

149 lines
2.7 KiB

defmodule Dagon.Listens.Listens do
@preloads [:artist, :album, :track]
@moduledoc """
The Listens.Listens context.
"""
import Ecto.Query, warn: false
alias Dagon.Repo
alias Dagon.Listens.Listens.Listen
@doc """
Returns the list of listens.
## Examples
iex> list_listens()
[%Listen{}, ...]
"""
def list_listens do
Listen
|> order_by(desc: :listened_at)
|> Repo.all()
|> Repo.preload(@preloads)
end
@doc """
Returns the limted list of listens.
## Examples
iex> list_listens(10)
[%Listen{}, ...]
"""
def list_listens(limit) do
Listen
|> order_by(desc: :listened_at)
|> limit(^limit)
|> Repo.all()
|> Repo.preload(@preloads)
end
def listens_per_month_by_artist(artist) do
Listen
|> select([l], [count(l.id), fragment("date_trunc('month', ?) as month", l.listened_at)])
|> order_by([l], fragment("date_trunc('month', ?)", l.listened_at))
|> group_by([l], fragment("date_trunc('month', ?)", l.listened_at))
|> where([l], l.artist_id == ^artist.id)
|> Repo.all()
end
@doc """
Gets a single listen.
Raises `Ecto.NoResultsError` if the Listen does not exist.
## Examples
iex> get_listen!(123)
%Listen{}
iex> get_listen!(456)
** (Ecto.NoResultsError)
"""
def get_listen!(id), do: Repo.get!(Listen, id) |> Repo.preload(@preloads)
def get_oldest_listen() do
Listen
|> order_by(asc: :listened_at)
|> limit(1)
|> Repo.one!()
end
def get_newest_listen() do
Listen
|> order_by(desc: :listened_at)
|> limit(1)
|> Repo.one!()
end
@doc """
Creates a listen.
## Examples
iex> create_listen(%{field: value})
{:ok, %Listen{}}
iex> create_listen(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_listen(attrs \\ %{}) do
%Listen{}
|> Listen.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a listen.
## Examples
iex> update_listen(listen, %{field: new_value})
{:ok, %Listen{}}
iex> update_listen(listen, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_listen(%Listen{} = listen, attrs) do
listen
|> Listen.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a Listen.
## Examples
iex> delete_listen(listen)
{:ok, %Listen{}}
iex> delete_listen(listen)
{:error, %Ecto.Changeset{}}
"""
def delete_listen(%Listen{} = listen) do
Repo.delete(listen)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking listen changes.
## Examples
iex> change_listen(listen)
%Ecto.Changeset{source: %Listen{}}
"""
def change_listen(%Listen{} = listen) do
Listen.changeset(listen, %{})
end
end