67 lines
1 KiB
Go
67 lines
1 KiB
Go
package state
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
)
|
|
|
|
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) GetItem(key string, item any) error {
|
|
data, ok := l.data[key]
|
|
if !ok {
|
|
return errors.New("Item not found")
|
|
}
|
|
|
|
err := json.Unmarshal(data, item)
|
|
return err
|
|
}
|
|
|
|
func (l *uniqueList) GetKeys() []string {
|
|
keys := make([]string, len(l.data))
|
|
|
|
i := 0
|
|
for k := range l.data {
|
|
keys[i] = k
|
|
i++
|
|
}
|
|
|
|
return keys
|
|
}
|