-
Notifications
You must be signed in to change notification settings - Fork 8
/
soft_collection.go
94 lines (77 loc) · 2.1 KB
/
soft_collection.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
package jsonapi
// SoftCollection is a collection of SoftResources where the type can be changed
// for all elements at once by modifying the Type field.
type SoftCollection struct {
Type *Type
col []*SoftResource
}
// SetType sets the collection's type.
func (s *SoftCollection) SetType(typ *Type) {
s.Type = typ
}
// GetType returns the collection's type.
func (s *SoftCollection) GetType() Type {
return *s.Type
}
// AddAttr adds an attribute to all of the resources in the collection.
func (s *SoftCollection) AddAttr(attr Attr) error {
return s.Type.AddAttr(attr)
}
// AddRel adds a relationship to all of the resources in the collection.
func (s *SoftCollection) AddRel(rel Rel) error {
return s.Type.AddRel(rel)
}
// Len returns the length of the collection.
func (s *SoftCollection) Len() int {
return len(s.col)
}
// At returns the element at index i.
func (s *SoftCollection) At(i int) Resource {
if i >= 0 && i < len(s.col) {
return s.col[i]
}
return nil
}
// Resource returns the element with an ID equal to id.
//
// It builds and returns a SoftResource with only the specified fields.
func (s *SoftCollection) Resource(id string, fields []string) Resource {
for i := range s.col {
if s.col[i].GetID() == id {
return s.col[i]
}
}
return nil
}
// Add creates a SoftResource and adds it to the collection.
func (s *SoftCollection) Add(r Resource) {
// A SoftResource is built from the Resource and
// then it is added to the collection.
sr := &SoftResource{}
sr.id = r.Get("id").(string)
sr.Type = s.Type
for _, attr := range r.Attrs() {
sr.AddAttr(attr)
sr.Set(attr.Name, r.Get(attr.Name))
}
for _, rel := range r.Rels() {
sr.AddRel(rel)
if rel.ToOne {
sr.Set(rel.FromName, r.Get(rel.FromName).(string))
} else {
sr.Set(rel.FromName, r.Get(rel.FromName).([]string))
}
}
s.col = append(s.col, sr)
}
// Remove removes the resource with an ID equal to id.
//
// Nothing happens if no resource has such an ID.
func (s *SoftCollection) Remove(id string) {
for i := range s.col {
if s.col[i].GetID() == id {
s.col = append(s.col[:i], s.col[i+1:]...)
return
}
}
}