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.

59 lines
1.2 KiB

  1. package stories
  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.Story, error) {
  12. story := models.Story{}
  13. err := collection.Find(query).One(&story)
  14. return story, err
  15. }
  16. func list(query interface{}, limit int) ([]models.Story, error) {
  17. stories := make([]models.Story, 0, 64)
  18. err := collection.Find(query).Limit(limit).Sort("-updatedDate").All(&stories)
  19. return stories, err
  20. }
  21. // makeStoryID makes a random story ID that's 16 characters long
  22. func makeStoryID() string {
  23. result := "S"
  24. offset := 0
  25. data := make([]byte, 32)
  26. rand.Read(data)
  27. for len(result) < 16 {
  28. result += strconv.FormatUint(binary.LittleEndian.Uint64(data[offset:]), 36)
  29. offset += 8
  30. if offset >= 32 {
  31. rand.Read(data)
  32. offset = 0
  33. }
  34. }
  35. return result[:16]
  36. }
  37. func init() {
  38. store.HandleInit(func(db *mgo.Database) {
  39. collection = db.C("story.stories")
  40. collection.EnsureIndexKey("tags")
  41. collection.EnsureIndexKey("author")
  42. collection.EnsureIndexKey("updatedDate")
  43. collection.EnsureIndexKey("fictionalDate")
  44. collection.EnsureIndexKey("listed")
  45. })
  46. }