-
Notifications
You must be signed in to change notification settings - Fork 0
/
repository.go
75 lines (61 loc) · 1.72 KB
/
repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package flatstorage
import (
"io/ioutil"
"reflect"
)
type GenericRepository[T any] struct {
*FlatStorage
collection string
}
func (r *GenericRepository[T]) Collection() string {
return r.collection
}
func (r *GenericRepository[T]) Count() int {
if !r.CollectionExists(r.Collection()) {
return 0
}
resources, err := ioutil.ReadDir(r.FlatStorage.collectionPath(r.Collection()))
if err != nil {
return -1
}
return len(resources)
}
func (r *GenericRepository[T]) Delete(resourceId string) error {
return r.FlatStorage.Delete(r.Collection(), resourceId)
}
func (r *GenericRepository[T]) DeleteAll() error {
return r.FlatStorage.DeleteAll(r.Collection())
}
func (r *GenericRepository[T]) Exists(resourceId string) bool {
return r.FlatStorage.Exists(r.Collection(), resourceId)
}
func (r *GenericRepository[T]) Get(resourceId string) (val *T, err error) {
err = r.Read(r.Collection(), resourceId, &val)
return
}
func (r *GenericRepository[T]) GetAll() (val []T, err error) {
values, err2 := r.ReadAll(r.Collection(), reflect.New(r.Type()).Interface())
err = err2
if err2 == nil {
for _, v := range values {
val = append(val, *v.(*T))
}
}
return
}
func (r *GenericRepository[T]) Type() reflect.Type {
return reflect.TypeOf((*T)(nil)).Elem()
}
func (r *GenericRepository[T]) Write(resourceId string, val T) error {
return r.FlatStorage.Write(r.Collection(), resourceId, val)
}
func Repository[T any](fs *FlatStorage) *GenericRepository[T] {
repo := &GenericRepository[T]{
FlatStorage: fs,
}
repo.collection = reflectTypeKey(repo.Type())
return repo
}
func NamedRepository[T any](fs *FlatStorage, collection string) *GenericRepository[T] {
return &GenericRepository[T]{collection: collection, FlatStorage: fs}
}