all repos — paprika @ lastfm

go rewrite of taigabot

database/db.go (view raw)

 1package database
 2
 3import (
 4	"path"
 5
 6	"git.icyphox.sh/paprika/config"
 7	"github.com/dgraph-io/badger/v3"
 8)
 9
10// Use this as a global DB handle.
11var DB database
12
13type database struct {
14	*badger.DB
15}
16
17func Open() (*badger.DB, error) {
18	db, err := badger.Open(
19		badger.DefaultOptions(path.Join(config.C.DbPath, "badger")),
20	)
21	if err != nil {
22		return nil, err
23	}
24	return db, nil
25}
26
27// Wrapper function to simplify setting a key/val
28// in badger.
29func (d *database) Set(key, val []byte) error {
30	err := d.Update(func(txn *badger.Txn) error {
31		err := txn.Set(key, val)
32		return err
33	})
34
35	return err
36}
37
38// Wrapper function to simplify getting a key from badger.
39func (d *database) Get(key []byte) ([]byte, error) {
40	var val []byte
41	err := d.View(func(txn *badger.Txn) error {
42		item, err := txn.Get(key)
43		if err != nil {
44			return err
45		}
46
47		err = item.Value(func(v []byte) error {
48			val, err = item.ValueCopy(nil)
49			return err
50		})
51		return err
52	})
53	if err != nil {
54		return nil, err
55	}
56	return val, nil
57}