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.7 KiB

  1. package change
  2. import (
  3. "log"
  4. "time"
  5. "git.aiterp.net/rpdata/api/model/counter"
  6. "git.aiterp.net/rpdata/api/internal/store"
  7. "github.com/globalsign/mgo"
  8. )
  9. var collection *mgo.Collection
  10. // A Change represents a change in any other model
  11. type Change struct {
  12. ID int `bson:"_id" json:"id"`
  13. Time time.Time `bson:"time" json:"time"`
  14. Model string `bson:"model" json:"model"`
  15. Op string `bson:"op" json:"op"`
  16. Author string `bson:"author,omitempty" json:"author,omitempty"`
  17. ObjectID string `bson:"objectId,omitempty" json:"objectId,omitempty"`
  18. Data interface{} `bson:"data,omitempty" json:"data,omitempty"`
  19. }
  20. // PublicModels lists which models can be listed in bulk by anyone.
  21. var PublicModels = []string{
  22. "Character",
  23. "Log",
  24. "Post",
  25. }
  26. // Submit submits a change to the history.
  27. func Submit(model, op, author, objectID string, data interface{}) (Change, error) {
  28. index, err := counter.Next("auto_increment", "Change")
  29. if err != nil {
  30. return Change{}, err
  31. }
  32. change := Change{
  33. ID: index,
  34. Time: time.Now(),
  35. Model: model,
  36. Op: op,
  37. Author: author,
  38. ObjectID: objectID,
  39. Data: data,
  40. }
  41. err = collection.Insert(&change)
  42. if err != nil {
  43. return Change{}, err
  44. }
  45. return change, err
  46. }
  47. func init() {
  48. store.HandleInit(func(db *mgo.Database) {
  49. collection = db.C("common.history")
  50. collection.EnsureIndexKey("model")
  51. collection.EnsureIndexKey("author")
  52. collection.EnsureIndexKey("objectId")
  53. err := collection.EnsureIndex(mgo.Index{
  54. Name: "expiry",
  55. Key: []string{"time"},
  56. ExpireAfter: time.Hour * 336,
  57. })
  58. if err != nil {
  59. log.Fatalln(err)
  60. }
  61. })
  62. }