Fakultas Ilmu Komputer UI

topic_controller.ex 1.29 KB
Newer Older
1
2
3
4
5
defmodule DiskuyWeb.TopicController do
  use DiskuyWeb, :controller

  alias Diskuy.Forum
  alias Diskuy.Forum.Topic
6
  alias Diskuy.Utility.Utility
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

  action_fallback DiskuyWeb.FallbackController

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

  def create(conn, %{"topic" => topic_params}) do
    with {:ok, %Topic{} = topic} <- Forum.create_topic(topic_params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", Routes.topic_path(conn, :show, topic))
      |> render("show.json", topic: topic)
    end
  end

  def show(conn, %{"id" => id}) do
25
26
27
    new_id = Utility.capitalize_string(id)
    topic = Forum.get_topic_by_name!(new_id)

28
29
30
31
    render(conn, "show.json", topic: topic)
  end

  def update(conn, %{"id" => id, "topic" => topic_params}) do
32
33
    new_id = Utility.capitalize_string(id)
    topic = Forum.get_topic_by_name!(new_id)
34
35
36
37
38
39
40

    with {:ok, %Topic{} = topic} <- Forum.update_topic(topic, topic_params) do
      render(conn, "show.json", topic: topic)
    end
  end

  def delete(conn, %{"id" => id}) do
41
42
    new_id = Utility.capitalize_string(id)
    topic = Forum.get_topic_by_name!(new_id)
43
44
45
46
47
48

    with {:ok, %Topic{}} <- Forum.delete_topic(topic) do
      send_resp(conn, :no_content, "")
    end
  end
end