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 change
  2. import (
  3. "log"
  4. "sync"
  5. "time"
  6. "git.aiterp.net/rpdata/api/model/counter"
  7. "git.aiterp.net/rpdata/api/internal/store"
  8. "github.com/globalsign/mgo"
  9. )
  10. var collection *mgo.Collection
  11. // A Change represents a change in any other model
  12. type Change struct {
  13. ID int `bson:"_id" json:"id"`
  14. Time time.Time `bson:"time" json:"time"`
  15. Model string `bson:"model" json:"model"`
  16. Op string `bson:"op" json:"op"`
  17. Author string `bson:"author,omitempty" json:"author,omitempty"`
  18. ObjectID string `bson:"objectId,omitempty" json:"objectId,omitempty"`
  19. Data interface{} `bson:"data,omitempty" json:"data,omitempty"`
  20. }
  21. // PublicModels lists which models can be listed in bulk by anyone.
  22. var PublicModels = []string{
  23. "Character",
  24. "Log",
  25. "Post",
  26. }
  27. var submitMutex sync.Mutex
  28. // Submit submits a change to the history.
  29. func Submit(model, op, author, objectID string, data interface{}) (Change, error) {
  30. submitMutex.Lock()
  31. defer submitMutex.Unlock()
  32. index, err := counter.Next("auto_increment", "Change")
  33. if err != nil {
  34. return Change{}, err
  35. }
  36. change := Change{
  37. ID: index,
  38. Time: time.Now(),
  39. Model: model,
  40. Op: op,
  41. Author: author,
  42. ObjectID: objectID,
  43. Data: data,
  44. }
  45. Timeline.push(change)
  46. err = collection.Insert(&change)
  47. if err != nil {
  48. return Change{}, err
  49. }
  50. return change, err
  51. }
  52. // FindID gets a change by ID
  53. func FindID(id int) (Change, error) {
  54. change := Change{}
  55. err := collection.FindId(id).One(&change)
  56. if err != nil {
  57. return Change{}, err
  58. }
  59. return change, nil
  60. }
  61. // List gets all changes in ascending order
  62. func List() ([]Change, error) {
  63. changes := make([]Change, 0, 64)
  64. err := collection.Find(nil).Sort("_id").All(&changes)
  65. if err != nil {
  66. return nil, err
  67. }
  68. return changes, nil
  69. }
  70. func init() {
  71. store.HandleInit(func(db *mgo.Database) {
  72. collection = db.C("common.history")
  73. collection.EnsureIndexKey("model")
  74. collection.EnsureIndexKey("author")
  75. collection.EnsureIndexKey("objectId")
  76. err := collection.EnsureIndex(mgo.Index{
  77. Name: "expiry",
  78. Key: []string{"time"},
  79. ExpireAfter: time.Hour * 336,
  80. })
  81. if err != nil {
  82. log.Fatalln(err)
  83. }
  84. })
  85. }