forked from ortuman/jackal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
57 lines (50 loc) · 1.37 KB
/
user.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
/*
* Copyright (c) 2018 Miguel Ángel Ortuño.
* See the LICENSE file for more information.
*/
package badgerdb
import (
"github.com/dgraph-io/badger"
"github.com/ortuman/jackal/model"
)
// InsertOrUpdateUser inserts a new user entity into storage,
// or updates it in case it's been previously inserted.
func (b *Storage) InsertOrUpdateUser(user *model.User) error {
return b.db.Update(func(tx *badger.Txn) error {
return b.insertOrUpdate(user, b.userKey(user.Username), tx)
})
}
// DeleteUser deletes a user entity from storage.
func (b *Storage) DeleteUser(username string) error {
return b.db.Update(func(tx *badger.Txn) error {
return b.delete(b.userKey(username), tx)
})
}
// FetchUser retrieves from storage a user entity.
func (b *Storage) FetchUser(username string) (*model.User, error) {
var usr model.User
err := b.fetch(&usr, b.userKey(username))
switch err {
case nil:
return &usr, nil
case errBadgerDBEntityNotFound:
return nil, nil
default:
return nil, err
}
}
// UserExists returns whether or not a user exists within storage.
func (b *Storage) UserExists(username string) (bool, error) {
err := b.fetch(nil, b.userKey(username))
switch err {
case nil:
return true, nil
case errBadgerDBEntityNotFound:
return false, nil
default:
return false, err
}
}
func (b *Storage) userKey(username string) []byte {
return []byte("users:" + username)
}