This repository was archived by the owner on Sep 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathcomment_controller.ex
More file actions
52 lines (41 loc) · 1.44 KB
/
comment_controller.ex
File metadata and controls
52 lines (41 loc) · 1.44 KB
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
defmodule RealWorldWeb.CommentController do
use RealWorldWeb, :controller
use RealWorldWeb.GuardedController
alias RealWorld.Blog
alias RealWorld.Blog.Comment
action_fallback(RealWorldWeb.FallbackController)
plug(Guardian.Plug.EnsureAuthenticated when action in [:create, :update, :delete])
def index(conn, %{"article_id" => slug}, _user) do
comments =
slug
|> Blog.get_article_by_slug!()
|> Blog.list_comments()
|> RealWorld.Repo.preload(:author)
render(conn, "index.json", comments: comments)
end
def create(conn, %{"article_id" => slug, "comment" => comment_params}, user) do
article = Blog.get_article_by_slug!(slug)
with {:ok, %Comment{} = comment} <-
Blog.create_comment(
comment_params
|> Map.merge(%{"user_id" => user.id})
|> Map.merge(%{"article_id" => article.id})
) do
conn
|> put_status(:created)
|> render("show.json", comment: comment)
end
end
def update(conn, %{"id" => id, "comment" => comment_params}, _user) do
comment = Blog.get_comment!(id)
with {:ok, %Comment{} = comment} <- Blog.update_comment(comment, comment_params) do
render(conn, "show.json", comment: comment)
end
end
def delete(conn, %{"id" => id}, _user) do
comment = Blog.get_comment!(id)
with {:ok, %Comment{}} <- Blog.delete_comment(comment) do
send_resp(conn, :no_content, "")
end
end
end