/
tag.go
85 lines (68 loc) · 1.31 KB
/
tag.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
package tag
import (
"fmt"
"github.com/google/uuid"
"unicode/utf8"
)
type Tag struct {
id string
name string
authorID string
}
func NewTag(name, authorID string) (*Tag, error) {
tg := Tag{
id: uuid.New().String(),
name: name,
authorID: authorID,
}
if err := tg.validate(); err != nil {
return nil, err
}
return &tg, nil
}
func (t *Tag) ID() string {
return t.id
}
func (t *Tag) AuthorID() string {
return t.authorID
}
func (t *Tag) ApplyChanges(tag string) error {
updated := *t
updated.name = tag
if err := updated.validate(); err != nil {
return err
}
t.name = tag
return nil
}
func (t *Tag) validate() error {
tagCount := utf8.RuneCountInString(t.name)
if tagCount < 2 {
return fmt.Errorf("name length should be at least 2 symbols, %d passed (%s)", tagCount, t.name)
}
if tagCount > 30 {
return fmt.Errorf("name max length is 30 symbols, %d passed (%s)", tagCount, t.name)
}
if t.authorID == "" {
return fmt.Errorf("authorID can not be empty")
}
return nil
}
func (t *Tag) ToMap() map[string]interface{} {
return map[string]interface{}{
"id": t.id,
"name": t.name,
"authorID": t.authorID,
}
}
func UnmarshalFromDB(
id string,
tag string,
authorID string,
) *Tag {
return &Tag{
id: id,
name: tag,
authorID: authorID,
}
}