forked from romshark/dgraph_graphql_go
/
reactionSubject.go
67 lines (61 loc) · 1.33 KB
/
reactionSubject.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
package dgraph
import (
"encoding/json"
"reflect"
"github.com/pkg/errors"
)
// ReactionSubject represents a union (Post | Reaction) type wrapper
type ReactionSubject struct {
V interface{}
}
// UID returns the unique entity node ID
func (u ReactionSubject) UID() *string {
switch v := u.V.(type) {
case *Post:
uid := v.UID
return &uid
case *Reaction:
uid := v.UID
return &uid
}
return nil
}
// MarshalJSON implements the Marshaler interface
func (u ReactionSubject) MarshalJSON() ([]byte, error) {
switch v := u.V.(type) {
case *Post:
return json.Marshal(v)
case *Reaction:
return json.Marshal(v)
}
panic(errors.Errorf(
"invalid union ReactionSubject value of type: %s",
reflect.TypeOf(u.V),
))
}
// UnmarshalJSON implements the Unmarshaler interface
func (u *ReactionSubject) UnmarshalJSON(d []byte) error {
var keyVal map[string]interface{}
if err := json.Unmarshal(d, &keyVal); err != nil {
return err
}
if _, exists := keyVal["Reaction.id"]; exists {
var v Reaction
if err := json.Unmarshal(d, &v); err != nil {
return err
}
u.V = &v
} else if _, exists := keyVal["Post.id"]; exists {
var v Post
if err := json.Unmarshal(d, &v); err != nil {
return err
}
u.V = &v
} else {
return errors.Errorf(
"unsupported JSON for union ReactionSubject: '%s'",
string(d),
)
}
return nil
}