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.

105 lines
2.2 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 fileRepository struct {
  11. files *mgo.Collection
  12. }
  13. func (r *fileRepository) Find(ctx context.Context, id string) (*models.File, error) {
  14. file := new(models.File)
  15. err := r.files.FindId(id).One(file)
  16. if err != nil {
  17. if err == mgo.ErrNotFound {
  18. return nil, repositories.ErrNotFound
  19. }
  20. return nil, err
  21. }
  22. return file, nil
  23. }
  24. func (r *fileRepository) List(ctx context.Context, filter models.FileFilter) ([]*models.File, error) {
  25. query := bson.M{}
  26. if filter.Author != nil {
  27. query["author"] = *filter.Author
  28. }
  29. if filter.MimeTypes != nil {
  30. query["mimeType"] = bson.M{"$in": filter.MimeTypes}
  31. }
  32. if filter.Public != nil {
  33. query["public"] = *filter.Public
  34. }
  35. files := make([]*models.File, 0, 16)
  36. err := r.files.Find(query).Sort("-date").All(&files)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return files, nil
  41. }
  42. func (r *fileRepository) Insert(ctx context.Context, file models.File) (*models.File, error) {
  43. file.ID = generate.FileID()
  44. err := r.files.Insert(&file)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return &file, nil
  49. }
  50. func (r *fileRepository) Update(ctx context.Context, file models.File, update models.FileUpdate) (*models.File, error) {
  51. updateBson := bson.M{}
  52. if update.Public != nil {
  53. updateBson["public"] = *update.Public
  54. file.Public = *update.Public
  55. }
  56. if update.Name != nil {
  57. updateBson["name"] = *update.Name
  58. file.Name = *update.Name
  59. }
  60. err := r.files.UpdateId(file.ID, bson.M{"$set": updateBson})
  61. if err != nil {
  62. return nil, err
  63. }
  64. return &file, nil
  65. }
  66. func (r *fileRepository) Delete(ctx context.Context, file models.File) error {
  67. return r.files.RemoveId(file.ID)
  68. }
  69. func newFileRepository(db *mgo.Database) (*fileRepository, error) {
  70. files := db.C("file.headers")
  71. err := files.EnsureIndexKey("author")
  72. if err != nil {
  73. return nil, err
  74. }
  75. err = files.EnsureIndexKey("mimeType")
  76. if err != nil {
  77. return nil, err
  78. }
  79. err = files.EnsureIndexKey("public")
  80. if err != nil {
  81. return nil, err
  82. }
  83. return &fileRepository{files: files}, nil
  84. }