frenzy/lib/frenzy_web/controllers/fervor/groups_controller.ex

102 lines
2.3 KiB
Elixir
Raw Normal View History

2019-03-31 14:52:56 +00:00
defmodule FrenzyWeb.Fervor.GroupsController do
use FrenzyWeb, :controller
alias Frenzy.{Repo, Group, Feed, Item}
import Ecto.Query
alias FrenzyWeb.Fervor.Paginator
plug :get_specific_group
def get_specific_group(%Plug.Conn{path_params: %{"id" => id}} = conn, _opts) do
user = conn.assigns[:user] |> Repo.preload(groups: [:feeds])
{id, _} = Integer.parse(id)
case Enum.find(user.groups, fn g -> g.id == id end) do
nil ->
conn
|> put_status(404)
|> json(%{error: "Unknown group"})
|> halt()
group ->
assign(conn, :group, group)
end
end
def get_specific_group(conn, _opts), do: conn
def groups_list(conn, _params) do
user = conn.assigns[:user] |> Repo.preload(groups: [:feeds])
groups = Enum.map(user.groups, &Group.to_fervor/1)
json(conn, groups)
end
def specific_group(conn, _params) do
group = conn.assigns[:group]
json(conn, Group.to_fervor(group))
end
def specific_group_feeds(conn, _params) do
group = conn.assigns[:group]
feeds = Enum.map(group.feeds, &Feed.to_fervor/1)
json(conn, feeds)
end
def specific_group_items(conn, params) do
group = conn.assigns[:group]
feed_ids = Enum.map(group.feeds, fn f -> f.id end)
query = from(i in Item, where: i.feed_id in ^feed_ids)
query =
case Map.get(params, "only") do
"read" -> from(i in query, where: i.read)
"unread" -> from(i in query, where: not i.read)
_ -> query
end
|> Paginator.paginate(params)
|> Paginator.limit(params)
items =
query
|> Repo.all()
|> Enum.map(&Item.to_fervor/1)
json(conn, items)
end
def create(conn, %{"title" => title}) do
user = conn.assigns[:user]
changeset =
Ecto.build_assoc(user, :groups, %{
title: title
})
{:ok, group} = Repo.insert(changeset)
group = Repo.preload(group, :feeds)
json(conn, Group.to_fervor(group))
end
def create(conn, _params) do
conn
|> put_status(400)
|> json(%{
error: "Could not create group",
error_description: "title parameter must be provided"
})
end
def delete(conn, _params) do
group = conn.assigns[:group]
{:ok, _} = Repo.delete(group)
send_resp(conn, 204, "")
end
end