2024-10-03 07:32:48 +02:00
|
|
|
package memory
|
2024-09-23 07:48:18 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"sort"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"go-mod.ewintr.nl/planner/item"
|
|
|
|
)
|
|
|
|
|
2024-10-03 07:32:48 +02:00
|
|
|
type Event struct {
|
2024-09-23 07:48:18 +02:00
|
|
|
events map[string]item.Event
|
|
|
|
mutex sync.RWMutex
|
|
|
|
}
|
|
|
|
|
2024-10-03 07:32:48 +02:00
|
|
|
func NewEvent() *Event {
|
|
|
|
return &Event{
|
2024-09-23 07:48:18 +02:00
|
|
|
events: make(map[string]item.Event),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-10-03 07:32:48 +02:00
|
|
|
func (r *Event) Find(id string) (item.Event, error) {
|
2024-09-23 07:48:18 +02:00
|
|
|
r.mutex.RLock()
|
|
|
|
defer r.mutex.RUnlock()
|
|
|
|
|
|
|
|
event, exists := r.events[id]
|
|
|
|
if !exists {
|
|
|
|
return item.Event{}, errors.New("event not found")
|
|
|
|
}
|
|
|
|
return event, nil
|
|
|
|
}
|
|
|
|
|
2024-10-03 07:32:48 +02:00
|
|
|
func (r *Event) FindAll() ([]item.Event, error) {
|
2024-09-23 07:48:18 +02:00
|
|
|
r.mutex.RLock()
|
|
|
|
defer r.mutex.RUnlock()
|
|
|
|
|
|
|
|
events := make([]item.Event, 0, len(r.events))
|
|
|
|
for _, event := range r.events {
|
|
|
|
events = append(events, event)
|
|
|
|
}
|
|
|
|
sort.Slice(events, func(i, j int) bool {
|
|
|
|
return events[i].ID < events[j].ID
|
|
|
|
})
|
|
|
|
|
|
|
|
return events, nil
|
|
|
|
}
|
|
|
|
|
2024-10-03 07:32:48 +02:00
|
|
|
func (r *Event) Store(e item.Event) error {
|
2024-09-23 07:48:18 +02:00
|
|
|
r.mutex.Lock()
|
|
|
|
defer r.mutex.Unlock()
|
|
|
|
|
|
|
|
r.events[e.ID] = e
|
2024-10-03 07:32:48 +02:00
|
|
|
|
2024-09-23 07:48:18 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-10-03 07:32:48 +02:00
|
|
|
func (r *Event) Delete(id string) error {
|
2024-09-23 07:48:18 +02:00
|
|
|
r.mutex.Lock()
|
|
|
|
defer r.mutex.Unlock()
|
|
|
|
|
|
|
|
if _, exists := r.events[id]; !exists {
|
|
|
|
return errors.New("event not found")
|
|
|
|
}
|
|
|
|
delete(r.events, id)
|
2024-10-03 07:32:48 +02:00
|
|
|
|
2024-09-23 07:48:18 +02:00
|
|
|
return nil
|
|
|
|
}
|