forked from irinazheltisheva/powergate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.go
More file actions
112 lines (99 loc) · 2.14 KB
/
Copy pathstore.go
File metadata and controls
112 lines (99 loc) · 2.14 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package source
import (
"encoding/json"
"errors"
"github.com/ipfs/go-datastore"
"github.com/ipfs/go-datastore/query"
logging "github.com/ipfs/go-log/v2"
)
var (
log = logging.Logger("reputation-source-store")
// ErrAlreadyExists returns when the soure already exists in Store
ErrAlreadyExists = errors.New("source already exists")
// ErrDoesntExists returns when the source isn't in the Store
ErrDoesntExists = errors.New("source doesn't exist")
baseKey = datastore.NewKey("/reputation/store")
)
// Store contains Sources information.
type Store struct {
ds datastore.TxnDatastore
}
// NewStore returns a new SourceStore.
func NewStore(ds datastore.TxnDatastore) *Store {
return &Store{
ds: ds,
}
}
// Add adds a new Source to the store.
func (ss *Store) Add(s Source) error {
txn, err := ss.ds.NewTransaction(false)
if err != nil {
return err
}
defer txn.Discard()
k := genKey(s.ID)
ok, err := txn.Has(k)
if err != nil {
return err
}
if ok {
return ErrAlreadyExists
}
return ss.put(txn, s)
}
// Update updates a Source.
func (ss *Store) Update(s Source) error {
txn, err := ss.ds.NewTransaction(false)
if err != nil {
return err
}
k := genKey(s.ID)
ok, err := txn.Has(k)
if err != nil {
return err
}
if !ok {
return ErrDoesntExists
}
return ss.put(txn, s)
}
// GetAll returns all Sources.
func (ss *Store) GetAll() ([]Source, error) {
txn, err := ss.ds.NewTransaction(true)
if err != nil {
return nil, err
}
defer txn.Discard()
q := query.Query{Prefix: baseKey.String()}
res, err := txn.Query(q)
if err != nil {
return nil, err
}
defer func() {
if err := res.Close(); err != nil {
log.Errorf("error when closing query result: %s", err)
}
}()
var ret []Source
for r := range res.Next() {
s := Source{}
if err := json.Unmarshal(r.Value, &s); err != nil {
return nil, err
}
ret = append(ret, s)
}
return ret, nil
}
func (ss *Store) put(txn datastore.Txn, s Source) error {
b, err := json.Marshal(s)
if err != nil {
return err
}
if err := txn.Put(genKey(s.ID), b); err != nil {
return err
}
return txn.Commit()
}
func genKey(id string) datastore.Key {
return baseKey.ChildString(id)
}