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.

51 lines
1.0 KiB

  1. package posts
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "errors"
  6. "strconv"
  7. "time"
  8. "git.aiterp.net/rpdata/api/internal/counter"
  9. "git.aiterp.net/rpdata/api/models"
  10. )
  11. // Add creates a new post.
  12. func Add(log models.Log, time time.Time, kind, nick, text string) (models.Post, error) {
  13. if kind == "" || nick == "" || text == "" {
  14. return models.Post{}, errors.New("Missing/empty parameters")
  15. }
  16. mutex.RLock()
  17. defer mutex.RUnlock()
  18. position, err := counter.Next("next_post_id", log.ShortID)
  19. if err != nil {
  20. return models.Post{}, err
  21. }
  22. post := models.Post{
  23. ID: generateID(time),
  24. Position: position,
  25. LogID: log.ShortID,
  26. Time: time,
  27. Kind: kind,
  28. Nick: nick,
  29. Text: text,
  30. }
  31. err = collection.Insert(post)
  32. if err != nil {
  33. return models.Post{}, err
  34. }
  35. return post, nil
  36. }
  37. func generateID(time time.Time) string {
  38. data := make([]byte, 4)
  39. rand.Read(data)
  40. return "P" + strconv.FormatInt(time.UnixNano(), 36) + strconv.FormatInt(int64(binary.LittleEndian.Uint32(data)), 36)
  41. }