/
db.go
93 lines (79 loc) · 1.94 KB
/
db.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
82
83
84
85
86
87
88
89
90
91
92
93
package service
import (
"bytes"
"encoding/gob"
"fmt"
"github.com/encloud-tech/encloud/pkg/storage/badger"
"github.com/encloud-tech/encloud/pkg/storage/couchbase"
"github.com/encloud-tech/encloud/pkg/types"
)
// New func implements the storage interface
func NewDB(config types.ConfYaml) *DB {
return &DB{
config: config,
}
}
type DB struct {
config types.ConfYaml
}
func initBadgerDB(cfg *types.ConfYaml) *badger.Storage {
badger := badger.New(cfg)
err := badger.Init()
if err != nil {
fmt.Printf("Error in initializing badger db : %s\n", err)
}
return badger
}
func initCouchBaseDB(cfg *types.ConfYaml) *couchbase.Storage {
couchbase := couchbase.New(cfg)
err := couchbase.Init()
if err != nil {
fmt.Printf("Error in initializing couchbase db : %s\n", err)
}
return couchbase
}
func (d *DB) Store(key string, fileMetaData types.FileMetadata) {
if d.config.Stat.StorageType == "couchbase" {
couchbase := initCouchBaseDB(&d.config)
couchbase.Create(key, fileMetaData)
} else {
badger := initBadgerDB(&d.config)
var b bytes.Buffer
e := gob.NewEncoder(&b)
if err := e.Encode(fileMetaData); err != nil {
panic(err)
}
badger.Create(key, b.Bytes())
badger.Close()
}
}
func (d *DB) FetchKeys() types.ListKeys {
var val types.ListKeys
couchbase := initCouchBaseDB(&d.config)
val = couchbase.FetchKeys()
return val
}
func (d *DB) Fetch(key string) types.FileData {
var val types.FileData
if d.config.Stat.StorageType == "couchbase" {
couchbase := initCouchBaseDB(&d.config)
val = couchbase.Read(key)
} else {
badger := initBadgerDB(&d.config)
val = badger.Read(key)
badger.Close()
}
return val
}
func (d *DB) FetchByCid(key string) types.FileMetadata {
var val types.FileMetadata
if d.config.Stat.StorageType == "couchbase" {
couchbase := initCouchBaseDB(&d.config)
val = couchbase.ReadByCid(key)
} else {
badger := initBadgerDB(&d.config)
val = badger.ReadByCid(key)
badger.Close()
}
return val
}