move DefaultRepository into own file; add todo tags;
This commit is contained in:
@@ -1,12 +1,5 @@
|
||||
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.
|
||||
@@ -18,73 +11,3 @@ type IRepository[T IIdentifiable] interface {
|
||||
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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user