-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathrepo.go
72 lines (60 loc) · 1.37 KB
/
repo.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
package grimoire
import (
"github.com/Fs02/grimoire/errors"
)
// Repo defines grimoire repository.
type Repo struct {
adapter Adapter
logger []Logger
inTransaction bool
}
// New create new repo using adapter.
func New(adapter Adapter) Repo {
return Repo{
adapter: adapter,
logger: []Logger{DefaultLogger},
}
}
// Adapter returns adapter of repo.
func (repo *Repo) Adapter() Adapter {
return repo.adapter
}
// SetLogger replace default logger with custom logger.
func (repo *Repo) SetLogger(logger ...Logger) {
repo.logger = logger
}
// From initiates a query for a collection.
func (repo Repo) From(collection string) Query {
return Query{
repo: &repo,
Collection: collection,
Fields: []string{collection + ".*"},
}
}
// Transaction performs transaction with given function argument.
func (repo Repo) Transaction(fn func(Repo) error) error {
adp, err := repo.adapter.Begin()
if err != nil {
return err
}
txRepo := New(adp)
txRepo.inTransaction = true
func() {
defer func() {
if p := recover(); p != nil {
txRepo.adapter.Rollback()
if e, ok := p.(errors.Error); ok && e.Kind() != errors.Unexpected {
err = e
} else {
panic(p) // re-throw panic after Rollback
}
} else if err != nil {
txRepo.adapter.Rollback()
} else {
err = txRepo.adapter.Commit()
}
}()
err = fn(txRepo)
}()
return err
}