Fakultas Ilmu Komputer UI

post_controller.ex 2.59 KB
Newer Older
1
2
3
4
5
defmodule DiskuyWeb.PostController do
  use DiskuyWeb, :controller

  alias Diskuy.Forum
  alias Diskuy.Forum.Post
6
7
  alias Diskuy.Likes
  alias Diskuy.Likes.PostLike
8
  alias DiskuyWeb.Auth.Guardian
9
10
11
12
13
14
15
16
17

  action_fallback DiskuyWeb.FallbackController

  def index(conn, _params) do
    posts = Forum.list_posts()
    render(conn, "index.json", posts: posts)
  end

  def create(conn, %{"post" => post_params}) do
18
19
    new_params = put_user_id(conn, %{"post" => post_params})
    with {:ok, %Post{} = post} <- Forum.create_post(new_params) do
20
21
22
23
24
25
26
27
28
29
30
31
32
      conn
      |> put_status(:created)
      |> put_resp_header("location", Routes.post_path(conn, :show, post))
      |> render("show.json", post: post)
    end
  end

  def show(conn, %{"id" => id}) do
    post = Forum.get_post!(id)
    render(conn, "show.json", post: post)
  end

  def update(conn, %{"id" => id, "post" => post_params}) do
33
    current_user = Guardian.Plug.current_resource(conn)
34
    post = Forum.get_post!(id)
35
    new_post_params = post_params |> Map.drop(["id", "points", "user_id", "thread_id"])
36
    with {:ok, :authorized} <- Guardian.check_authorized(current_user, post.user_id),
37
         {:ok, %Post{} = post} <- Forum.update_post(post, new_post_params) do
38
39
40
41
42
      render(conn, "show.json", post: post)
    end
  end

  def delete(conn, %{"id" => id}) do
43
    current_user = Guardian.Plug.current_resource(conn)
44
45
    post = Forum.get_post!(id)

46
47
    with {:ok, :authorized} <- Guardian.check_authorized(current_user, post.user_id),
         {:ok, %Post{}} <- Forum.delete_post(post) do
48
49
50
      send_resp(conn, :no_content, "")
    end
  end
51

52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
  def add_like(conn, %{"id" => id}) do
    current_user = Guardian.Plug.current_resource(conn)
    post = Forum.get_post!(id)

    with {:ok, %PostLike{}} <- Likes.create_post_like(%{"user_id" => current_user.id,
                                                        "post_id" => id}),
         {:ok, %Post{} = post} <- Forum.update_post(post, %{"points" => (post.points+1)}) do
         render(conn, "show.json", post: post)
    end
  end

  def delete_like(conn, %{"id" => id}) do
    current_user = Guardian.Plug.current_resource(conn)
    post = Forum.get_post!(id)
    post_like = Likes.get_post_like_by_refer!(current_user.id, id)

    with {:ok, %PostLike{}} <- Likes.delete_post_like(post_like),
         {:ok, %Post{}} <- Forum.update_post(post, %{"points" => (post.points-1)}) do
         render(conn, "show.json", post: post)
    end
  end

74
75
76
77
78
79
  defp put_user_id(conn, %{"post" => post_params}) do
    current_user = Guardian.Plug.current_resource(conn)
    new_params = Map.put(post_params, "user_id", current_user.id)
    new_params
  end

80
end