This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
/
tEditReaction.go
140 lines (127 loc) · 2.53 KB
/
tEditReaction.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package dgraph
import (
"context"
"encoding/json"
"github.com/dgraph-io/dgo/protos/api"
"github.com/romshark/dgraph_graphql_go/api/graph/auth"
"github.com/romshark/dgraph_graphql_go/store"
strerr "github.com/romshark/dgraph_graphql_go/store/errors"
)
// EditReaction edits an existing reaction
func (str *impl) EditReaction(
ctx context.Context,
reaction store.ID,
editor store.ID,
newMessage string,
) (
result store.Reaction,
changes struct {
Message bool
},
err error,
) {
result.ID = reaction
// Begin transaction
txn, close := str.txn(&err)
if err != nil {
return
}
defer close()
// Ensure reaction and editor exist
var qr struct {
Reaction []Reaction `json:"reaction"`
Editor []User `json:"editor"`
}
err = txn.QueryVars(
ctx,
`query Reaction(
$id: string,
$editorId: string
) {
reaction(func: eq(Reaction.id, $id)) {
uid
Reaction.subject {
uid
Post.id
Reaction.id
}
Reaction.author {
uid
User.id
}
Reaction.creation
Reaction.emotion
Reaction.message
}
editor(func: eq(User.id, $editorId)) { uid }
}`,
map[string]string{
"$id": string(reaction),
"$editorId": string(editor),
},
&qr,
)
if err != nil {
return
}
if len(qr.Reaction) < 1 {
err = strerr.New(strerr.ErrInvalidInput, "reaction not found")
return
}
if len(qr.Editor) < 1 {
err = strerr.Newf(strerr.ErrInvalidInput, "editor not found")
return
}
// Check permission
if err = auth.Authorize(ctx, auth.IsOwner{
Owner: store.ID(qr.Reaction[0].Author[0].ID),
}); err != nil {
return
}
result.Message = newMessage
if qr.Reaction[0].Message != newMessage {
changes.Message = true
}
react := qr.Reaction[0]
result.UID = react.UID
result.Creation = react.Creation
result.Author = &store.User{
GraphNode: store.GraphNode{
UID: react.Author[0].UID,
},
}
result.Emotion = react.Emotion
switch subject := react.Subject[0].V.(type) {
case *Post:
result.Subject = store.Post{
GraphNode: store.GraphNode{
UID: subject.UID,
},
}
case *Reaction:
result.Subject = store.Reaction{
GraphNode: store.GraphNode{
UID: subject.UID,
},
}
}
// Edit the reaction
var mutatedReactionJSON []byte
mutatedReactionJSON, err = json.Marshal(struct {
UID string `json:"uid"`
NewMessage string `json:"Reaction.message"`
}{
UID: result.UID,
NewMessage: newMessage,
})
if err != nil {
return
}
_, err = txn.Mutation(ctx, &api.Mutation{
SetJson: mutatedReactionJSON,
})
if err != nil {
return
}
return
}