76 lines
2.0 KiB
Go
76 lines
2.0 KiB
Go
package data
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"strconv"
|
|
)
|
|
|
|
|
|
// Default implementation of IRepository using an IDatastore.
|
|
type DefaultRepository[T IIdentifiable] struct {
|
|
ds IDatastore
|
|
prefix string
|
|
}
|
|
|
|
// TODO docstring
|
|
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
|
|
}
|