-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
67 lines (58 loc) · 1.56 KB
/
conn.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
package graphify
import (
"context"
"reflect"
"github.com/arangodb/go-driver"
"github.com/arangodb/go-driver/http"
)
// IConnection ...
type IConnection interface {
// GetDatabase ...
GetDatabase(ctx context.Context) (driver.Database, error)
// GetCollection ...
GetCollection(ctx context.Context, elem reflect.Type) (driver.Collection, error)
}
type connection struct {
database driver.Database
}
// NewConnection ...
func NewConnection(ctx context.Context, conf DatabaseConfig) *connection {
conn, err := http.NewConnection(conf.Connection)
if err != nil {
panic(err)
}
client, err := driver.NewClient(driver.ClientConfig{
Connection: conn,
Authentication: driver.BasicAuthentication(conf.UserName, conf.Password),
})
if err != nil {
panic("failed to establish connection")
}
exists, err := client.DatabaseExists(ctx, conf.DBName)
if err != nil {
panic("failed to check database existence")
}
if exists {
db, err := client.Database(ctx, conf.DBName)
if err != nil {
panic("failed to connect to database")
}
return &connection{database: db}
} else {
db, err := client.CreateDatabase(ctx, conf.DBName, nil)
if err != nil {
panic("failed to create database")
}
return &connection{database: db}
}
}
func (c *connection) GetDatabase(ctx context.Context) (db driver.Database, err error) {
return c.database, nil
}
func (c *connection) GetCollection(ctx context.Context, elem reflect.Type) (driver.Collection, error) {
db, err := c.GetDatabase(ctx)
if err != nil {
return nil, err
}
return db.Collection(ctx, CollectionFor(elem))
}