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.

94 lines
2.3 KiB

  1. package changes
  2. import (
  3. "strconv"
  4. "time"
  5. "git.aiterp.net/rpdata/api/internal/counter"
  6. "git.aiterp.net/rpdata/api/models"
  7. )
  8. // Submit a change to the database. The objects may be any supported model, or arrays.
  9. func Submit(model, op, author string, listed bool, keys []models.ChangeKey, objects ...interface{}) (models.Change, error) {
  10. submitMutex.Lock()
  11. defer submitMutex.Unlock()
  12. id, err := counter.Next("auto_increment", "Change")
  13. if err != nil {
  14. return models.Change{}, err
  15. }
  16. if !models.ChangeModel(model).IsValid() {
  17. panic("Invalid model")
  18. }
  19. // Silently discard * keys on unlisted changes.
  20. if !listed {
  21. keysCopy := make([]models.ChangeKey, len(keys))
  22. copy(keysCopy, keys)
  23. keys = keysCopy
  24. deletes := make([]int, 0, 1)
  25. for i, key := range keys {
  26. if key.ID == "*" {
  27. deletes = append(deletes, i-len(deletes))
  28. }
  29. }
  30. for _, index := range deletes {
  31. keys = append(keys[:index], keys[index+1:]...)
  32. }
  33. }
  34. change := models.Change{
  35. ID: "Change_" + strconv.Itoa(id),
  36. Model: models.ChangeModel(model),
  37. Date: time.Now(),
  38. Op: op,
  39. Author: author,
  40. Keys: keys,
  41. Listed: listed,
  42. }
  43. for _, object := range objects {
  44. switch object := object.(type) {
  45. case models.Log:
  46. change.Logs = append(change.Logs, object)
  47. case []models.Log:
  48. change.Logs = append(change.Logs, object...)
  49. case models.Character:
  50. change.Characters = append(change.Characters, object)
  51. case []models.Character:
  52. change.Characters = append(change.Characters, object...)
  53. case models.Channel:
  54. change.Channels = append(change.Channels, object)
  55. case []models.Channel:
  56. change.Channels = append(change.Channels, object...)
  57. case models.Post:
  58. change.Posts = append(change.Posts, object)
  59. case []models.Post:
  60. change.Posts = append(change.Posts, object...)
  61. case models.Story:
  62. change.Stories = append(change.Stories, object)
  63. case []models.Story:
  64. change.Stories = append(change.Stories, object...)
  65. case models.Tag:
  66. change.Tags = append(change.Tags, object)
  67. case []models.Tag:
  68. change.Tags = append(change.Tags, object...)
  69. case models.Chapter:
  70. change.Chapters = append(change.Chapters, object)
  71. case []models.Chapter:
  72. change.Chapters = append(change.Chapters, object...)
  73. }
  74. }
  75. // TODO: Push to subscribers
  76. err = collection.Insert(&change)
  77. if err != nil {
  78. return models.Change{}, err
  79. }
  80. return change, nil
  81. }