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.

75 lines
1.5 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. restoreIDs bool
  12. keys *mgo.Collection
  13. }
  14. func newKeyRepository(db *mgo.Database, restoreIDs bool) (repositories.KeyRepository, error) {
  15. collection := db.C("auth.keys")
  16. err := collection.EnsureIndexKey("user")
  17. if err != nil {
  18. return nil, err
  19. }
  20. return &keyRepository{
  21. keys: collection,
  22. restoreIDs: restoreIDs,
  23. }, nil
  24. }
  25. func (r *keyRepository) Find(ctx context.Context, id string) (*models.Key, error) {
  26. key := models.Key{}
  27. err := r.keys.FindId(id).One(&key)
  28. if err != nil {
  29. return nil, err
  30. }
  31. return &key, err
  32. }
  33. func (r *keyRepository) List(ctx context.Context, filter models.KeyFilter) ([]*models.Key, error) {
  34. query := bson.M{}
  35. if filter.UserID != nil {
  36. query["user"] = *filter.UserID
  37. }
  38. keys := make([]*models.Key, 0, 4)
  39. err := r.keys.Find(query).All(&keys)
  40. if err != nil {
  41. if err == mgo.ErrNotFound {
  42. return nil, nil
  43. }
  44. return nil, err
  45. }
  46. return keys, nil
  47. }
  48. func (r *keyRepository) Insert(ctx context.Context, key models.Key) (*models.Key, error) {
  49. if !r.restoreIDs {
  50. key.ID = generate.KeyID()
  51. }
  52. err := r.keys.Insert(&key)
  53. if err != nil {
  54. return nil, err
  55. }
  56. return &key, nil
  57. }
  58. func (r *keyRepository) Delete(ctx context.Context, key models.Key) error {
  59. return r.keys.RemoveId(key.ID)
  60. }