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.

55 lines
1.3 KiB

  1. package logs
  2. import (
  3. "errors"
  4. "strconv"
  5. "time"
  6. "git.aiterp.net/rpdata/api/internal/counter"
  7. "git.aiterp.net/rpdata/api/models"
  8. "git.aiterp.net/rpdata/api/models/channels"
  9. "github.com/globalsign/mgo/bson"
  10. )
  11. // Add creates a new Log
  12. func Add(date time.Time, channelName, title, eventName, description string, open bool) (models.Log, error) {
  13. nextID, err := counter.Next("auto_increment", "Log")
  14. if err != nil {
  15. return models.Log{}, errors.New("Failed to allocate short ID: " + err.Error())
  16. }
  17. _, err = channels.Ensure(channelName, open)
  18. if err != nil {
  19. return models.Log{}, errors.New("Failed to ensure channel: " + err.Error())
  20. }
  21. log := models.Log{
  22. ID: makeLogID(date, channelName),
  23. ShortID: "L" + strconv.Itoa(nextID),
  24. Date: date,
  25. ChannelName: channelName,
  26. Title: title,
  27. EventName: eventName,
  28. Description: description,
  29. Open: open,
  30. CharacterIDs: nil,
  31. }
  32. err = collection.Insert(log)
  33. if err != nil {
  34. return models.Log{}, err
  35. }
  36. // There can be only one open log in the same channel. TODO: Transaction
  37. if open {
  38. query := bson.M{
  39. "_id": bson.M{"$ne": log.ID},
  40. "open": true,
  41. "channel": log.ChannelName,
  42. }
  43. go collection.UpdateAll(query, bson.M{"$set": bson.M{"open": false}})
  44. }
  45. return log, nil
  46. }