-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentities.go
81 lines (67 loc) · 1.34 KB
/
entities.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
76
77
78
79
80
81
package stream
import (
"encoding/json"
"fmt"
)
type Entity interface {
ID() string
Version() int64
}
type Entities[E Entity] interface {
One(E) error // todo One(Events) (E, error)
Read([]E, []byte) error
Update(...E) error
Delete(...E) error
}
type NewEntities[E Entity] func() Entities[E]
// todo use https://github.com/hashicorp/go-memdb
type entities[E Entity] struct {
store map[string][]byte
}
func NewMemoryEntities[E Entity]() Entities[E] {
return &entities[E]{
store: make(map[string][]byte),
}
}
func (r *entities[E]) One(d E) error {
b, found := r.store[d.ID()]
if !found {
return ErrDocumentNotFound
}
return json.Unmarshal(b, &d)
}
func (r *entities[E]) Read(ee []E, bytes []byte) error {
var i int
for _, body := range r.store {
if err := json.Unmarshal(body, &ee[i]); err != nil {
return err
}
i++
}
return nil
}
func (r *entities[E]) Update(e ...E) error {
for i := range e {
b, err := json.Marshal(e[i])
if err != nil {
return err
}
r.store[e[i].ID()] = b
}
return nil
}
func (r *entities[E]) Delete(e ...E) error {
//TODO implement me
panic("implement me")
}
func (r *entities[E]) Count() int {
return len(r.store)
}
func (r *entities[E]) String() string {
var e E
var s = fmt.Sprintf("%T\n", e)
for i := range r.store {
s += fmt.Sprintf("%s\n", string(r.store[i]))
}
return s
}