You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
package bolt
import ( "context" "github.com/gisle/stufflog/database/repositories" "github.com/gisle/stufflog/models" "github.com/gisle/stufflog/slerrors" "github.com/vmihailenco/msgpack/v4" "go.etcd.io/bbolt" )
var bnUsers = []byte("User")
type userRepository struct { db *bbolt.DB }
func (r *userRepository) FindID(ctx context.Context, id string) (*models.User, error) { user := new(models.User) err := r.db.View(func(tx *bbolt.Tx) error { value := tx.Bucket(bnUsers).Get(unsafeStringToBytes(id)) if value == nil { return slerrors.NotFound("User") } err := msgpack.Unmarshal(value, user) if err != nil { return err } return nil }) if err != nil { return nil, err }
return user, nil }
func (r *userRepository) List(ctx context.Context) ([]*models.User, error) { users := make([]*models.User, 0, 16) err := r.db.View(func(tx *bbolt.Tx) error { cursor := tx.Bucket(bnUsers).Cursor()
for key, value := cursor.First(); key != nil; key, value = cursor.Next() { user := new(models.User) err := msgpack.Unmarshal(value, user) if err != nil { return err }
users = append(users, user) }
return nil }) if err != nil { return nil, err }
return users, nil }
func (r *userRepository) Save(ctx context.Context, user models.User) error { value, err := msgpack.Marshal(&user) if err != nil { return err }
return r.db.Update(func(tx *bbolt.Tx) error { return tx.Bucket(bnUsers).Put(unsafeStringToBytes(user.ID), value) }) }
func (r *userRepository) Remove(ctx context.Context, user models.User) error { return r.db.Update(func(tx *bbolt.Tx) error { return tx.Bucket(bnUsers).Delete(unsafeStringToBytes(user.ID)) }) }
func newUserRepository(db *bbolt.DB) (repositories.UserRepository, error) { err := db.Update(func(tx *bbolt.Tx) error { _, err := tx.CreateBucketIfNotExists(bnUsers) return err }) if err != nil { return nil, err }
return &userRepository{ db: db, }, nil }
|