-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomponent.go
76 lines (67 loc) · 1.96 KB
/
component.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
package portfolio
import (
"fmt"
"net/url"
"regexp"
"slices"
"strings"
"gopkg.in/yaml.v3"
)
const (
ComponentTypeSecurity = "Security"
ComponentTypePortfolio = "Portfolio"
ComponentTypeEquity = "Equity"
ComponentTypeETF = "ETF"
ComponentTypeFactor = "Factor"
ComponentTypeMutualFund = "Mutual Fund"
)
func ComponentTypes() []string {
return []string{
ComponentTypeSecurity,
ComponentTypePortfolio,
ComponentTypeEquity,
ComponentTypeETF,
ComponentTypeFactor,
ComponentTypeMutualFund,
}
}
type Component struct {
Type string `yaml:"type,omitempty" json:"type,omitempty" bson:"type"`
ID string `yaml:"id,omitempty" json:"id,omitempty" bson:"id"`
Label string `yaml:"label,omitempty" json:"label,omitempty" bson:"label"`
}
var componentExpression = regexp.MustCompile(`^[a-zA-Z0-9.:]{1,24}$`)
func (component *Component) Validate() error {
if component.ID == "" {
return fmt.Errorf(`component ID must be set`)
}
if component.ID == "undefined" {
return fmt.Errorf(`component ID must not be "undefined"`)
}
if !componentExpression.MatchString(component.ID) {
return fmt.Errorf("component id %q does not match the component ID pattern %q", component.ID, componentExpression.String())
}
if component.Type != "" && !slices.Contains(ComponentTypes(), component.Type) {
return fmt.Errorf("component type %q is not a known component type", component.Type)
}
return nil
}
func (component *Component) marshalURLValues(q url.Values, prefix string) {
q.Add(strings.Join([]string{prefix, "id"}, "-"), component.ID)
}
func (component *Component) UnmarshalYAML(value *yaml.Node) error {
switch value.Kind {
case yaml.ScalarNode:
return value.Decode(&component.ID)
case yaml.MappingNode:
type C Component
var c C
if err := value.Decode(&c); err != nil {
return err
}
*component = Component(c)
return nil
default:
return fmt.Errorf("wrong YAML type: expected either a component identifier (string) or a Component")
}
}