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.

69 lines
1.4 KiB

  1. package mongodb
  2. import (
  3. "context"
  4. "git.aiterp.net/rpdata/api/internal/generate"
  5. "git.aiterp.net/rpdata/api/models"
  6. "git.aiterp.net/rpdata/api/repositories"
  7. "github.com/globalsign/mgo"
  8. "github.com/globalsign/mgo/bson"
  9. )
  10. type keyRepository struct {
  11. keys *mgo.Collection
  12. }
  13. func newKeyRepository(db *mgo.Database) (repositories.KeyRepository, error) {
  14. collection := db.C("auth.keys")
  15. err := collection.EnsureIndexKey("user")
  16. if err != nil {
  17. return nil, err
  18. }
  19. return &keyRepository{keys: collection}, nil
  20. }
  21. func (r *keyRepository) Find(ctx context.Context, id string) (*models.Key, error) {
  22. key := models.Key{}
  23. err := r.keys.FindId(id).One(&key)
  24. if err != nil {
  25. return nil, err
  26. }
  27. return &key, err
  28. }
  29. func (r *keyRepository) List(ctx context.Context, filter models.KeyFilter) ([]*models.Key, error) {
  30. query := bson.M{}
  31. if filter.UserID != nil {
  32. query["user"] = *filter.UserID
  33. }
  34. keys := make([]*models.Key, 0, 4)
  35. err := r.keys.Find(query).All(&keys)
  36. if err != nil {
  37. if err == mgo.ErrNotFound {
  38. return nil, nil
  39. }
  40. return nil, err
  41. }
  42. return keys, nil
  43. }
  44. func (r *keyRepository) Insert(ctx context.Context, key models.Key) (*models.Key, error) {
  45. key.ID = generate.KeyID()
  46. err := r.keys.Insert(&key)
  47. if err != nil {
  48. return nil, err
  49. }
  50. return &key, nil
  51. }
  52. func (r *keyRepository) Delete(ctx context.Context, key models.Key) error {
  53. return r.keys.RemoveId(key.ID)
  54. }