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.

61 lines
1.2 KiB

  1. package chapters
  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. var storyCollection *mgo.Collection
  12. func find(query interface{}) (models.Chapter, error) {
  13. chapter := models.Chapter{}
  14. err := collection.Find(query).One(&chapter)
  15. return chapter, err
  16. }
  17. func list(query interface{}) ([]models.Chapter, error) {
  18. chapters := make([]models.Chapter, 0, 8)
  19. err := collection.Find(query).Sort("createdDate").All(&chapters)
  20. if err != nil {
  21. return nil, err
  22. }
  23. return chapters, nil
  24. }
  25. func makeChapterID() string {
  26. result := "SC"
  27. offset := 0
  28. data := make([]byte, 32)
  29. rand.Read(data)
  30. for len(result) < 24 {
  31. result += strconv.FormatUint(binary.LittleEndian.Uint64(data[offset:]), 36)
  32. offset += 8
  33. if offset >= 32 {
  34. rand.Read(data)
  35. offset = 0
  36. }
  37. }
  38. return result[:24]
  39. }
  40. func init() {
  41. store.HandleInit(func(db *mgo.Database) {
  42. collection = db.C("story.chapters")
  43. storyCollection = db.C("story.stories")
  44. collection.EnsureIndexKey("storyId")
  45. collection.EnsureIndexKey("author")
  46. collection.EnsureIndexKey("createdDate")
  47. })
  48. }