-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_favorite.rb
47 lines (36 loc) Β· 1.32 KB
/
add_favorite.rb
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
44
45
46
47
class Mutations::AddFavorite < Mutations::BaseMutation
description "Add post to favorite"
argument :postId, ID, required: true
field :favorite, Types::PostType, null: true
field :success, Boolean, null: false
field :errors, [String], null: false
def resolve(args)
unless context[:current_user]
raise Exception, "Sign in to do this action"
end
post = Post.find(args[:post_id])
if context[:current_user] == post.user
raise Exception, "You can't add to favorite your own post"
end
if Favorite.exists?(user: context[:current_user], post: post)
raise Exception, "you have added this post in favorites"
end
favorite = Favorite.new(
post: post,
user: context[:current_user]
)
if favorite.save
return {
favorite: post,
success: true,
errors: favorite.errors.full_messages
}
else
raise ActiveRecord::RecordInvalid, favorite
end
rescue ActiveRecord::RecordInvalid => invalid
return { errors: invalid.record.errors.full_messages, success: false }
rescue Exception => e
{ errors: e.message.split(",") , success: false}
end
end