Files
crowsnest/internal/data/IRepository.go

91 lines
2.4 KiB
Go

package data
import (
"encoding/json"
"errors"
"strconv"
)
// An interface to manage generic structure objects persistently. Should use an
// IDatastore as the interface that actually stores and retrieves the data from
// an external source.
type IRepository[T IIdentifiable] interface {
Create(t T) error
Update(t T) error
Delete(t T) error
GetAll() ([]T, error)
GetById(id uint) (T, error)
GetByCriteria(c ISearchCriteria[T]) ([]T, error)
}
// --- default implementation ---
type DefaultRepository[T IIdentifiable] struct {
ds IDatastore
prefix string
}
func NewDefaultRepository[T IIdentifiable](ds IDatastore, prefix string) *DefaultRepository[T] {
return &DefaultRepository[T]{ ds: ds, prefix: prefix }
}
// Creates a new entry in the repository with the given object t. Throws an
// error if there already exists an entry with the same id, the json encoding
// fails or the connection to the IDatastore fails.
func (repo *DefaultRepository[T]) Create(t T) error {
key := repo.prefix + ":" + strconv.FormatUint(uint64(t.Id()), 10)
exists, err := repo.ds.KeyExists(key)
if err != nil { return err }
if exists { return errors.New("key already exits") }
d, err := json.Marshal(t)
if err != nil { return err }
err = repo.ds.Set(key, string(d))
if err != nil { return err }
return nil
}
// Updates the entry with the same id as t in the repository with the values of
// t. Trows an error if the json encoding fails or the connection to the
// IDatastore fails.
func (repo *DefaultRepository[T]) Update(t T) error {
key := repo.prefix + ":" + strconv.FormatUint(uint64(t.Id()), 10)
exists, err := repo.ds.KeyExists(key)
if err != nil { return err }
if !exists { return errors.New("key does not exits") }
d, err := json.Marshal(t)
if err != nil { return err }
err = repo.ds.Set(key, string(d))
if err != nil { return err }
return nil
}
func (repo *DefaultRepository[T]) Delete(t T) error {
// TODO
return nil
}
func (repo *DefaultRepository[T]) GetAll() ([]T, error) {
// TODO
return nil, nil
}
func (repo *DefaultRepository[T]) GetById(id uint) (T, error) {
// TODO
return *new(T), nil
}
func (repo *DefaultRepository[T]) GetByCriteria(c ISearchCriteria[T]) ([]T, error) {
// TODO
return nil, nil
}