Fakultas Ilmu Komputer UI

Commit 2125ff4e authored by Muhammad Rafif Elfazri's avatar Muhammad Rafif Elfazri
Browse files

Add like system by for thread

parent c8e47158
......@@ -3,6 +3,8 @@ defmodule DiskuyWeb.ThreadController do
alias Diskuy.Forum
alias Diskuy.Forum.Thread
alias Diskuy.Likes
alias Diskuy.Likes.ThreadLike
alias DiskuyWeb.Auth.Guardian
action_fallback DiskuyWeb.FallbackController
......@@ -41,6 +43,28 @@ defmodule DiskuyWeb.ThreadController do
end
end
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)
thread_like = Likes.get_thread_like_by_refer!(id, current_user.id)
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
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)
......
......@@ -3,6 +3,7 @@ defmodule DiskuyWeb.ThreadLikeController do
alias Diskuy.Likes
alias Diskuy.Likes.ThreadLike
alias DiskuyWeb.Auth.Guardian
action_fallback DiskuyWeb.FallbackController
......@@ -40,4 +41,11 @@ defmodule DiskuyWeb.ThreadLikeController do
send_resp(conn, :no_content, "")
end
end
def check_like(conn, %{"id" => id}) do
current_user = Guardian.Plug.current_resource(conn)
thread_like = Likes.get_thread_like_by_refer!(id, current_user.id)
render(conn, "show.json", thread_like: thread_like)
end
end
......@@ -16,6 +16,12 @@ defmodule DiskuyWeb.Router do
resources "/threads", ThreadController, except: [:new, :edit, :show, :index]
resources "/topics", TopicController, except: [:new, :edit, :show, :index]
resources "/post", PostController, except: [:new, :edit, :show, :index]
post "/threads/like/:id", ThreadController, :add_like
options "/threads/like/:id", ThreadController, :options
post "/threads/dislike/:id", ThreadController, :delete_like
options "/threads/dislike/:id", ThreadController, :options
get "/threads/checklike/:id", ThreadLikeController, :check_like
options "/threads/checklike/:id", ThreadLikeController, :options
end
scope "/api", DiskuyWeb do
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment