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.

66 lines
1.2 KiB

  1. package comments
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "strconv"
  6. "git.aiterp.net/rpdata/api/internal/store"
  7. "git.aiterp.net/rpdata/api/models"
  8. "github.com/globalsign/mgo"
  9. )
  10. var collection *mgo.Collection
  11. func find(query interface{}) (models.Comment, error) {
  12. comment := models.Comment{}
  13. err := collection.Find(query).One(&comment)
  14. return comment, err
  15. }
  16. func list(query interface{}, limit int) ([]models.Comment, error) {
  17. allocSize := 32
  18. if limit >= 0 {
  19. allocSize = limit
  20. } else {
  21. limit = 0
  22. }
  23. comments := make([]models.Comment, 0, allocSize)
  24. err := collection.Find(query).Sort("createdDate").Limit(limit).All(&comments)
  25. if err != nil {
  26. return nil, err
  27. }
  28. return comments, nil
  29. }
  30. func makeCommentID() string {
  31. result := "SCC"
  32. offset := 0
  33. data := make([]byte, 48)
  34. rand.Read(data)
  35. for len(result) < 32 {
  36. result += strconv.FormatUint(binary.LittleEndian.Uint64(data[offset:]), 36)
  37. offset += 8
  38. if offset >= 48 {
  39. rand.Read(data)
  40. offset = 0
  41. }
  42. }
  43. return result[:32]
  44. }
  45. func init() {
  46. store.HandleInit(func(db *mgo.Database) {
  47. collection = db.C("story.comments")
  48. collection.EnsureIndexKey("chapterId")
  49. collection.EnsureIndexKey("author")
  50. collection.EnsureIndexKey("createdDate")
  51. })
  52. }