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.

80 lines
1.9 KiB

  1. package mongodb
  2. import (
  3. "context"
  4. "git.aiterp.net/rpdata/api/models"
  5. "github.com/globalsign/mgo"
  6. "github.com/globalsign/mgo/bson"
  7. )
  8. type channelRepository struct {
  9. channels *mgo.Collection
  10. }
  11. func (r *channelRepository) Find(ctx context.Context, name string) (*models.Channel, error) {
  12. channel := new(models.Channel)
  13. err := r.channels.FindId(name).One(channel)
  14. if err != nil {
  15. return nil, err
  16. }
  17. return channel, nil
  18. }
  19. func (r *channelRepository) List(ctx context.Context, filter models.ChannelFilter) ([]*models.Channel, error) {
  20. query := bson.M{}
  21. if filter.Logged != nil {
  22. query["logged"] = *filter.Logged
  23. }
  24. if filter.EventName != nil {
  25. query["eventName"] = *filter.EventName
  26. }
  27. if filter.LocationName != nil {
  28. query["locationName"] = *filter.LocationName
  29. }
  30. channels := make([]*models.Channel, 0, 32)
  31. err := r.channels.Find(query).Limit(filter.Limit).Sort("_id").All(&channels)
  32. if err != nil {
  33. if err == mgo.ErrNotFound {
  34. return channels, nil
  35. }
  36. return nil, err
  37. }
  38. return channels, nil
  39. }
  40. func (r *channelRepository) Insert(ctx context.Context, channel models.Channel) (*models.Channel, error) {
  41. err := r.channels.Insert(&channel)
  42. if err != nil {
  43. return nil, err
  44. }
  45. return &channel, nil
  46. }
  47. func (r *channelRepository) Update(ctx context.Context, channel models.Channel, update models.ChannelUpdate) (*models.Channel, error) {
  48. updateBson := bson.M{}
  49. if update.Logged != nil {
  50. updateBson["logged"] = *update.Logged
  51. }
  52. if update.LocationName != nil {
  53. updateBson["locationName"] = *update.LocationName
  54. }
  55. if update.EventName != nil {
  56. updateBson["eventName"] = *update.EventName
  57. }
  58. err := r.channels.UpdateId(channel.Name, bson.M{"$set": updateBson})
  59. if err != nil {
  60. return nil, err
  61. }
  62. return &channel, nil
  63. }
  64. func (r *channelRepository) Remove(ctx context.Context, channel models.Channel) error {
  65. return r.channels.RemoveId(channel.Name)
  66. }