defmodule DiskuyWeb.PostController do use DiskuyWeb, :controller alias Diskuy.Forum alias Diskuy.Forum.Post alias Diskuy.Likes alias Diskuy.Likes.PostLike alias DiskuyWeb.Auth.Guardian action_fallback DiskuyWeb.FallbackController def index(conn, _params) do posts = Forum.list_posts() render(conn, "index.json", posts: posts) end def create(conn, %{"post" => post_params}) do new_params = put_user_id(conn, %{"post" => post_params}) with {:ok, %Post{} = post} <- Forum.create_post(new_params) do conn |> put_status(:created) |> put_resp_header("location", Routes.post_path(conn, :show, post)) |> render("show.json", post: post) end end def show(conn, %{"id" => id}) do post = Forum.get_post!(id) render(conn, "show.json", post: post) end def update(conn, %{"id" => id, "post" => post_params}) do current_user = Guardian.Plug.current_resource(conn) post = Forum.get_post!(id) new_post_params = post_params |> Map.drop(["id", "points", "user_id", "thread_id"]) with {:ok, :authorized} <- Guardian.check_authorized(current_user, post.user_id), {:ok, %Post{} = post} <- Forum.update_post(post, new_post_params) do render(conn, "show.json", post: post) end end def delete(conn, %{"id" => id}) do current_user = Guardian.Plug.current_resource(conn) post = Forum.get_post!(id) with {:ok, :authorized} <- Guardian.check_authorized(current_user, post.user_id), {:ok, %Post{}} <- Forum.delete_post(post) do send_resp(conn, :no_content, "") end end def add_like(conn, %{"id" => id}) do current_user = Guardian.Plug.current_resource(conn) post = Forum.get_post!(id) with {:ok, %PostLike{}} <- Likes.create_post_like(%{"user_id" => current_user.id, "post_id" => id}), {:ok, %Post{} = post} <- Forum.update_post(post, %{"points" => (post.points+1)}) do render(conn, "show.json", post: post) end end def delete_like(conn, %{"id" => id}) do current_user = Guardian.Plug.current_resource(conn) post = Forum.get_post!(id) post_like = Likes.get_post_like_by_refer!(current_user.id, id) with {:ok, %PostLike{}} <- Likes.delete_post_like(post_like), {:ok, %Post{}} <- Forum.update_post(post, %{"points" => (post.points-1)}) do render(conn, "show.json", post: post) end end defp put_user_id(conn, %{"post" => post_params}) do current_user = Guardian.Plug.current_resource(conn) new_params = Map.put(post_params, "user_id", current_user.id) new_params end end