Skip to content
This repository was archived by the owner on Nov 8, 2022. It is now read-only.

Commit 7b58c62

Browse files
committed
refactor: use Multi to refactor delete_comment
1 parent fc050cf commit 7b58c62

File tree

2 files changed

+31
-9
lines changed

2 files changed

+31
-9
lines changed

lib/mastani_server/accounts/delegates/favorite_category.ex

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ defmodule MastaniServer.Accounts.Delegate.FavoriteCategory do
3131
end
3232

3333
def delete_favorite_category(%User{id: user_id}, id) do
34-
# TODO: refactor delete_comment by use Multi
3534
with {:ok, category} <- FavoriteCategory |> ORM.find_by(~m(id user_id)a) do
3635
Multi.new()
3736
|> Multi.run(:delete_category, fn _ ->

lib/mastani_server/cms/delegates/comment_curd.ex

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
defmodule MastaniServer.CMS.Delegate.CommentCURD do
2+
@moduledoc """
3+
CURD for comments
4+
"""
25
import Ecto.Query, warn: false
36
import Helper.Utils, only: [done: 1]
7+
import Helper.ErrorCode
8+
49
import MastaniServer.CMS.Utils.Matcher
510
import ShortMaps
611

712
alias MastaniServer.{Repo, Accounts}
813
alias Helper.{ORM, QueryBuilder}
914
alias MastaniServer.CMS.{PostCommentReply, JobCommentReply}
1015

16+
alias Ecto.Multi
17+
1118
@doc """
1219
Creates a comment for psot, job ...
1320
"""
@@ -38,20 +45,36 @@ defmodule MastaniServer.CMS.Delegate.CommentCURD do
3845
def delete_comment(thread, content_id) do
3946
with {:ok, action} <- match_action(thread, :comment),
4047
{:ok, comment} <- ORM.find(action.reactor, content_id) do
41-
# TODO: should use Nulti
42-
case ORM.delete(comment) do
43-
{:ok, comment} ->
48+
Multi.new()
49+
|> Multi.run(:delete_comment, fn _ ->
50+
ORM.delete(comment)
51+
end)
52+
|> Multi.run(:update_floor, fn _ ->
53+
ret =
4454
Repo.update_all(
4555
from(p in action.reactor, where: p.id > ^comment.id),
4656
inc: [floor: -1]
4757
)
58+
|> done()
59+
60+
case ret do
61+
{:ok, _} -> {:ok, comment}
62+
_ -> {:error, ""}
63+
end
64+
end)
65+
|> Repo.transaction()
66+
|> delete_comment_result()
67+
end
68+
end
4869

49-
{:ok, comment}
70+
defp delete_comment_result({:ok, %{delete_comment: result}}), do: {:ok, result}
5071

51-
{:error, error} ->
52-
{:error, error}
53-
end
54-
end
72+
defp delete_comment_result({:error, :delete_comment, result, _steps}) do
73+
{:error, [message: "delete comment fails", code: ecode(:delete_fails)]}
74+
end
75+
76+
defp delete_comment_result({:error, :update_floor, _result, _steps}) do
77+
{:error, [message: "update follor fails", code: ecode(:delete_fails)]}
5578
end
5679

5780
def list_comments(thread, content_id, %{page: page, size: size} = filters) do

0 commit comments

Comments
 (0)