Fakultas Ilmu Komputer UI

thread_controller.ex 1.13 KB
Newer Older
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
defmodule DiskuyWeb.ThreadController do
  use DiskuyWeb, :controller

  alias Diskuy.Forum
  alias Diskuy.Forum.Thread

  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
    with {:ok, %Thread{} = thread} <- Forum.create_thread(thread_params) do
      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
end