github.com/martinohmann/rfoutlet@v1.2.1-0.20220707195255-8a66aa411105/internal/outlet/registry.go (about) 1 package outlet 2 3 import "fmt" 4 5 // Registry holds references to all outlets and outlet groups. 6 type Registry struct { 7 outlets []*Outlet 8 outletMap map[string]*Outlet 9 groups []*Group 10 groupMap map[string]*Group 11 } 12 13 // NewRegistry creates a new *Registry. 14 func NewRegistry() *Registry { 15 return &Registry{ 16 outlets: make([]*Outlet, 0), 17 outletMap: make(map[string]*Outlet), 18 groups: make([]*Group, 0), 19 groupMap: make(map[string]*Group), 20 } 21 } 22 23 // RegisterGroups registers groups and the outlets contained in those groups. 24 // Returns an error if groups or outlets with duplicate IDs are found. 25 func (r *Registry) RegisterGroups(groups ...*Group) error { 26 for _, group := range groups { 27 _, ok := r.groupMap[group.ID] 28 if ok { 29 return fmt.Errorf("duplicate group ID %q", group.ID) 30 } 31 32 err := r.RegisterOutlets(group.Outlets...) 33 if err != nil { 34 return err 35 } 36 37 r.groupMap[group.ID] = group 38 r.groups = append(r.groups, group) 39 40 log.WithField("groupID", group.ID).Info("registered outlet group") 41 } 42 43 return nil 44 } 45 46 // RegisterOutlets registers outlets. Returns an error if outlets with duplicate 47 // IDs are found. 48 func (r *Registry) RegisterOutlets(outlets ...*Outlet) error { 49 for _, outlet := range outlets { 50 _, ok := r.outletMap[outlet.ID] 51 if ok { 52 return fmt.Errorf("duplicate outlet ID %q", outlet.ID) 53 } 54 55 r.outletMap[outlet.ID] = outlet 56 r.outlets = append(r.outlets, outlet) 57 58 log.WithField("outletID", outlet.ID).Info("registered outlet") 59 } 60 61 return nil 62 } 63 64 // GetOutlet fetches the an outlet from the registry by ID. The second return 65 // value is true if the outlet was found, false otherwise. 66 func (r *Registry) GetOutlet(id string) (*Outlet, bool) { 67 outlet, ok := r.outletMap[id] 68 return outlet, ok 69 } 70 71 // GetOutlets returns all registered outlets. 72 func (r *Registry) GetOutlets() []*Outlet { 73 return r.outlets 74 } 75 76 // GetGroup fetches the an group from the registry by ID. The second return 77 // value is true if the group was found, false otherwise. 78 func (r *Registry) GetGroup(id string) (*Group, bool) { 79 group, ok := r.groupMap[id] 80 return group, ok 81 } 82 83 // GetGroups returns all registered groups. 84 func (r *Registry) GetGroups() []*Group { 85 return r.groups 86 }