Remove BPA operator
[icn.git] / cmd / bpa-restapi-agent / internal / db / store.go
1 package db
2
3 import (
4         "encoding/json"
5         "reflect"
6
7         pkgerrors "github.com/pkg/errors"
8 )
9
10 // DBconn interface used to talk to a concrete Database connection
11 var DBconn Store
12
13 // Key is an interface that will be implemented by anypackage
14 // that wants to use the Store interface. This allows various
15 // db backends and key types.
16 type Key interface {
17         String() string
18 }
19
20 // Store is an interface for accessing a database
21 type Store interface {
22         // Returns nil if db health is good
23         HealthCheck() error
24
25         // Unmarshal implements any unmarshaling needed for the database
26         Unmarshal(inp []byte, out interface{}) error
27
28         // Creates a new master table with key and links data with tag and
29         // creates a pointer to the newly added data in the master table
30         Create(table string, key Key, tag string, data interface{}) error
31
32         // Reads data for a particular key with specific tag.
33         Read(table string, key Key, tag string) ([]byte, error)
34
35         // Update data for particular key with specific tag
36         Update(table string, key Key, tag string, data interface{}) error
37
38         // Deletes a specific tag data for key.
39         // TODO: If tag is empty, it will delete all tags under key.
40         Delete(table string, key Key, tag string) error
41
42         // Reads all master tables and data from the specified tag in table
43         ReadAll(table string, tag string) (map[string][]byte, error)
44 }
45
46 // CreateDBClient creates the DB client
47 func CreateDBClient(dbType string) error {
48         var err error
49         switch dbType {
50         case "mongo":
51                 // create a mongodb database with ICN as the name
52                 DBconn, err = NewMongoStore("icn", nil)
53         default:
54                 return pkgerrors.New(dbType + "DB not supported")
55         }
56         return err
57 }
58
59 // Serialize converts given data into a JSON string
60 func Serialize(v interface{}) (string, error) {
61         out, err := json.Marshal(v)
62         if err != nil {
63                 return "", pkgerrors.Wrap(err, "Error serializing "+reflect.TypeOf(v).String())
64         }
65         return string(out), nil
66 }
67
68 // DeSerialize converts string to a json object specified by type
69 func DeSerialize(str string, v interface{}) error {
70         err := json.Unmarshal([]byte(str), &v)
71         if err != nil {
72                 return pkgerrors.Wrap(err, "Error deSerializing "+str)
73         }
74         return nil
75 }