62 lines
1 KiB
Go
62 lines
1 KiB
Go
package state
|
|
|
|
import (
|
|
"encoding/json"
|
|
"reflect"
|
|
)
|
|
|
|
type uniqueList struct {
|
|
store StateStore
|
|
storeKey string
|
|
data map[string][]byte
|
|
}
|
|
|
|
func NewUniqueList(store StateStore, storeKey string) uniqueList {
|
|
l := uniqueList{store: store}
|
|
l.data = make(map[string][]byte)
|
|
l.storeKey = storeKey
|
|
|
|
return l
|
|
}
|
|
|
|
func (l *uniqueList) persist() error {
|
|
err := l.store.StoreState(l.storeKey, l.data)
|
|
return err
|
|
}
|
|
|
|
func (l *uniqueList) AddItem(key string, item any) error {
|
|
data, err := json.Marshal(item)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
l.data[key] = data
|
|
err = l.persist()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (l *uniqueList) ItemExists(key string) (bool, error) {
|
|
_, ok := l.data[key]
|
|
return ok, nil
|
|
}
|
|
|
|
func (l *uniqueList) GetList(data []any) error {
|
|
element := reflect.TypeOf(data).Elem()
|
|
var err error
|
|
|
|
for _, dataByte := range l.data {
|
|
new := reflect.New(element)
|
|
err = json.Unmarshal(dataByte, &new)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
data = append(data, new)
|
|
}
|
|
|
|
return nil
|
|
}
|