stufflog graphql server
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.

99 lines
2.2 KiB

  1. package mysqldriver
  2. import (
  3. "context"
  4. "database/sql"
  5. "errors"
  6. "git.aiterp.net/stufflog/server/internal/slerrors"
  7. "git.aiterp.net/stufflog/server/models"
  8. sq "github.com/Masterminds/squirrel"
  9. "github.com/jmoiron/sqlx"
  10. )
  11. type userRepository struct {
  12. db *sqlx.DB
  13. }
  14. func (r *userRepository) Find(ctx context.Context, id string) (*models.User, error) {
  15. user := models.User{}
  16. err := r.db.GetContext(ctx, &user, "SELECT * FROM user WHERE user_id=?", id)
  17. if err != nil {
  18. if err == sql.ErrNoRows {
  19. return nil, slerrors.NotFound("User")
  20. }
  21. return nil, err
  22. }
  23. return &user, nil
  24. }
  25. func (r *userRepository) List(ctx context.Context, filter models.UserFilter) ([]*models.User, error) {
  26. q := sq.Select("user.*").From("user").OrderBy("user_id")
  27. if len(filter.UserIDs) > 0 {
  28. q = q.Where(sq.Eq{"user_id": filter.UserIDs})
  29. }
  30. if filter.Active != nil {
  31. q = q.Where(sq.Eq{"active": *filter.Active})
  32. }
  33. if filter.Admin != nil {
  34. q = q.Where(sq.Eq{"admin": *filter.Admin})
  35. }
  36. if filter.Limit != nil && *filter.Limit > 0 {
  37. q = q.Limit(uint64(*filter.Limit))
  38. }
  39. query, args, err := q.ToSql()
  40. if err != nil {
  41. return nil, err
  42. }
  43. results := make([]*models.User, 0, 16)
  44. err = r.db.SelectContext(ctx, &results, query, args...)
  45. if err != nil {
  46. if err == sql.ErrNoRows {
  47. return []*models.User{}, nil
  48. }
  49. return nil, err
  50. }
  51. return results, nil
  52. }
  53. func (r *userRepository) Insert(ctx context.Context, user models.User) (*models.User, error) {
  54. if len(user.Name) < 1 || len([]byte(user.Name)) > 32 {
  55. return nil, errors.New("user id is not valid")
  56. }
  57. _, err := r.db.NamedExecContext(ctx, `
  58. INSERT INTO user (
  59. user_id, name, active, admin, hash
  60. ) VALUES (
  61. :user_id, :name, :active, :admin, :hash
  62. )
  63. `, user)
  64. if err != nil {
  65. return nil, err
  66. }
  67. return &user, nil
  68. }
  69. func (r *userRepository) Save(ctx context.Context, user models.User) error {
  70. _, err := r.db.NamedExecContext(ctx, `
  71. UPDATE user
  72. SET name=:name,
  73. hash=:hash,
  74. admin=:admin,
  75. active=:active
  76. WHERE user_id=:user_id
  77. `, user)
  78. return err
  79. }
  80. func (r *userRepository) Delete(ctx context.Context, user models.User) error {
  81. _, err := r.db.ExecContext(ctx, "DELETE FROM user WHERE user_id=?", user.ID)
  82. return err
  83. }