Plan stuff. Log stuff.
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.

91 lines
1.9 KiB

5 years ago
  1. package bolt
  2. import (
  3. "context"
  4. "github.com/gisle/stufflog/database/repositories"
  5. "github.com/gisle/stufflog/models"
  6. "github.com/gisle/stufflog/slerrors"
  7. "github.com/vmihailenco/msgpack/v4"
  8. "go.etcd.io/bbolt"
  9. )
  10. var bnUsers = []byte("User")
  11. type userRepository struct {
  12. db *bbolt.DB
  13. }
  14. func (r *userRepository) FindID(ctx context.Context, id string) (*models.User, error) {
  15. user := new(models.User)
  16. err := r.db.View(func(tx *bbolt.Tx) error {
  17. value := tx.Bucket(bnUsers).Get(unsafeStringToBytes(id))
  18. if value == nil {
  19. return slerrors.NotFound("User")
  20. }
  21. err := msgpack.Unmarshal(value, user)
  22. if err != nil {
  23. return err
  24. }
  25. return nil
  26. })
  27. if err != nil {
  28. return nil, err
  29. }
  30. return user, nil
  31. }
  32. func (r *userRepository) List(ctx context.Context) ([]*models.User, error) {
  33. users := make([]*models.User, 0, 16)
  34. err := r.db.View(func(tx *bbolt.Tx) error {
  35. cursor := tx.Bucket(bnUsers).Cursor()
  36. for key, value := cursor.First(); key != nil; key, value = cursor.Next() {
  37. user := new(models.User)
  38. err := msgpack.Unmarshal(value, user)
  39. if err != nil {
  40. return err
  41. }
  42. users = append(users, user)
  43. }
  44. return nil
  45. })
  46. if err != nil {
  47. return nil, err
  48. }
  49. return users, nil
  50. }
  51. func (r *userRepository) Save(ctx context.Context, user models.User) error {
  52. value, err := msgpack.Marshal(&user)
  53. if err != nil {
  54. return err
  55. }
  56. return r.db.Update(func(tx *bbolt.Tx) error {
  57. return tx.Bucket(bnUsers).Put(unsafeStringToBytes(user.ID), value)
  58. })
  59. }
  60. func (r *userRepository) Remove(ctx context.Context, user models.User) error {
  61. return r.db.Update(func(tx *bbolt.Tx) error {
  62. return tx.Bucket(bnUsers).Delete(unsafeStringToBytes(user.ID))
  63. })
  64. }
  65. func newUserRepository(db *bbolt.DB) (repositories.UserRepository, error) {
  66. err := db.Update(func(tx *bbolt.Tx) error {
  67. _, err := tx.CreateBucketIfNotExists(bnUsers)
  68. return err
  69. })
  70. if err != nil {
  71. return nil, err
  72. }
  73. return &userRepository{
  74. db: db,
  75. }, nil
  76. }