-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtag.go
More file actions
106 lines (88 loc) · 2.02 KB
/
tag.go
File metadata and controls
106 lines (88 loc) · 2.02 KB
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
package jsonapi
import (
"fmt"
"reflect"
"strings"
)
const (
tagName = "jsonapi"
tagAttribute = "attr"
tagPrimary = "primary"
tagRelation = "relation"
tagIgnore = "-"
)
type Tag interface {
IsAttribute() bool
GetAttributeName() (string, error)
IsPrimary() bool
GetTypeIdentifier() (string, error)
IsRelation() bool
GetRelationName() (string, error)
IsIgnore() bool
}
type coreTag struct {
hasAttribute bool
hasPrimary bool
hasRelation bool
hasIgnore bool
value string
}
func (tag *coreTag) IsAttribute() bool {
return tag.hasAttribute
}
func (tag *coreTag) IsPrimary() bool {
return tag.hasPrimary
}
func (tag *coreTag) IsRelation() bool {
return tag.hasRelation
}
func (tag *coreTag) IsIgnore() bool {
return tag.hasIgnore
}
func (tag *coreTag) GetAttributeName() (string, error) {
if tag.IsAttribute() {
return tag.value, nil
}
return "", fmt.Errorf("Tag does not represent an attribute")
}
func (tag *coreTag) GetRelationName() (string, error) {
if tag.IsRelation() {
return tag.value, nil
}
return "", fmt.Errorf("Tag does not represent a relation")
}
func (tag *coreTag) GetTypeIdentifier() (string, error) {
if tag.IsPrimary() {
return tag.value, nil
}
return "", fmt.Errorf("Tag does not represent the model type")
}
func ParseTag(field reflect.StructField) (Tag, error) {
tagValue := field.Tag.Get(tagName)
tag := &coreTag{}
if tagValue == "" {
// No tag then we assume an attribute
tag.hasAttribute = true
tag.value = field.Name
return tag, nil
}
parts := strings.Split(tagValue, ",")
switch parts[0] {
case tagAttribute:
tag.hasAttribute = true
case tagPrimary:
tag.hasPrimary = true
case tagRelation:
tag.hasRelation = true
case tagIgnore:
tag.hasIgnore = true
return tag, nil
default:
return nil, fmt.Errorf("'%s' is an invalid jsonapi struct tag", tagValue)
}
if !tag.IsIgnore() && (len(parts) < 2 || len(parts) > 3) {
return nil, fmt.Errorf("'%s' is an invalid jsonapi struct tag", tagValue)
}
tag.value = parts[1]
return tag, nil
}