GraphQL API and utilities for the rpdata project
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.

52 lines
1.1 KiB

  1. package mongodb
  2. import (
  3. "context"
  4. "git.aiterp.net/rpdata/api/models"
  5. "git.aiterp.net/rpdata/api/repositories"
  6. "github.com/globalsign/mgo"
  7. "github.com/globalsign/mgo/bson"
  8. )
  9. type userRepository struct {
  10. users *mgo.Collection
  11. }
  12. func newUserRepository(db *mgo.Database) (repositories.UserRepository, error) {
  13. collection := db.C("core.users")
  14. return &userRepository{users: collection}, nil
  15. }
  16. func (r *userRepository) Find(ctx context.Context, id string) (*models.User, error) {
  17. user := new(models.User)
  18. err := r.users.FindId(id).One(user)
  19. if err != nil {
  20. if err == mgo.ErrNotFound {
  21. return nil, repositories.ErrNotFound
  22. }
  23. return nil, err
  24. }
  25. return user, nil
  26. }
  27. func (r *userRepository) List(ctx context.Context) ([]*models.User, error) {
  28. users := make([]*models.User, 0, 8)
  29. err := r.users.Find(bson.M{}).All(&users)
  30. if err != nil && err != mgo.ErrNotFound {
  31. return nil, err
  32. }
  33. return users, nil
  34. }
  35. func (r *userRepository) Insert(ctx context.Context, user models.User) (*models.User, error) {
  36. err := r.users.Insert(user)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return &user, nil
  41. }