Fakultas Ilmu Komputer UI

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

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

  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
16
17
    new_params = put_user_id(conn, %{"thread" => thread_params})
    with {:ok, %Thread{} = thread} <- Forum.create_thread(new_params) do
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
      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
43
44
45
46
47
48

  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
49
end