Fakultas Ilmu Komputer UI

thread_controller.ex 2.4 KB
Newer Older
1
2
3
4
5
defmodule DiskuyWeb.ThreadController do
  use DiskuyWeb, :controller

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

  action_fallback DiskuyWeb.FallbackController

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

  def create(conn, %{"thread" => thread_params}) do
18
19
    new_params = put_user_id(conn, %{"thread" => thread_params})
    with {:ok, %Thread{} = thread} <- Forum.create_thread(new_params) do
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
      conn
      |> put_status(:created)
      |> put_resp_header("location", Routes.thread_path(conn, :show, thread))
      |> render("show.json", thread: thread)
    end
  end

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

  def update(conn, %{"id" => id, "thread" => thread_params}) do
    thread = Forum.get_thread!(id)
    with {:ok, %Thread{} = thread} <- Forum.update_thread(thread, thread_params) do
      render(conn, "show.json", thread: thread)
    end
  end

  def delete(conn, %{"id" => id}) do
    thread = Forum.get_thread!(id)
    with {:ok, %Thread{}} <- Forum.delete_thread(thread) do
      send_resp(conn, :no_content, "")
    end
  end
45

46
47
48
49
50
51
52
53
54
55
56
57
58
59
  def add_like(conn, %{"id" => id}) do
    current_user = Guardian.Plug.current_resource(conn)
    thread = Forum.get_thread!(id)

    with {:ok, %ThreadLike{} = _thread_like} <- Likes.create_thread_like(%{"user_id" => current_user.id,
                                                                           "thread_id" => id}),
         {:ok, %Thread{} = thread} <- Forum.update_thread(thread, %{"points" => (thread.points+ 1)}) do
         render(conn, "show.json", thread: thread)
    end
  end

  def delete_like(conn, %{"id" => id}) do
    current_user = Guardian.Plug.current_resource(conn)
    thread = Forum.get_thread!(id)
Muhammad Rafif Elfazri's avatar
Muhammad Rafif Elfazri committed
60
    thread_like = Likes.get_thread_like_by_refer!(current_user.id, id)
61
62
63
64
65
66
67

    with {:ok, %ThreadLike{}} <- Likes.delete_thread_like(thread_like),
         {:ok, %Thread{} = thread} <- Forum.update_thread(thread, %{"points" => (thread.points-1)}) do
         render(conn, "show.json", thread: thread)
    end
  end

68
69
70
71
72
  defp put_user_id(conn, %{"thread" => thread_params}) do
    current_user = Guardian.Plug.current_resource(conn)
    new_params = Map.put(thread_params, "user_id", current_user.id)
    new_params
  end
73
end