This repository has been archived by the owner on Aug 28, 2023. It is now read-only.
/
store.go
79 lines (68 loc) · 1.66 KB
/
store.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
package dgraph
import (
"context"
"log"
"github.com/dgraph-io/dgo"
"github.com/dgraph-io/dgo/protos/api"
"github.com/pkg/errors"
"github.com/romshark/dgraph_graphql_go/store"
"google.golang.org/grpc"
)
// impl represents the service store
type impl struct {
host string
db *dgo.Dgraph
comparePassword func(hash, password string) bool
onClose func()
debugLog *log.Logger
errorLog *log.Logger
}
// NewStore creates a new disconnected database client instance
func NewStore(
host string,
comparePassword func(hash, password string) bool,
debugLog *log.Logger,
errorLog *log.Logger,
) store.Store {
return &impl{
host: host,
db: nil,
comparePassword: comparePassword,
debugLog: debugLog,
errorLog: errorLog,
}
}
// Prepare prepares the store for use
func (str *impl) Prepare() error {
if str.db != nil {
return nil
}
conn, err := grpc.Dial(str.host, grpc.WithInsecure())
if err != nil {
return errors.Wrap(err, "gRPC dial")
}
str.debugLog.Printf("database (%s) connected", str.host)
str.db = dgo.NewDgraphClient(api.NewDgraphClient(conn))
str.onClose = func() {
if err := conn.Close(); err != nil {
str.errorLog.Printf("closing db conn: %s", err)
}
str.db = nil
str.onClose = nil
}
err = str.setupSchema(context.Background())
if err != nil {
str.debugLog.Print("database schema setup")
}
return err
}
// IsActive returns true if the store is operational, otherwise returns false
func (str *impl) IsActive() bool {
return str.db != nil
}
func (str *impl) ensureActive() error {
if str.IsActive() {
return nil
}
return errors.New("store inactive")
}