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.

64 lines
1.2 KiB

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