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.

62 lines
1.2 KiB

5 years ago
5 years ago
5 years ago
  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. if err != nil {
  15. return nil, err
  16. }
  17. return &story, err
  18. }
  19. func list(query interface{}, limit int) ([]models.Story, error) {
  20. stories := make([]models.Story, 0, 64)
  21. err := collection.Find(query).Limit(limit).Sort("-updatedDate").All(&stories)
  22. return stories, err
  23. }
  24. // makeStoryID makes a random story ID that's 16 characters long
  25. func makeStoryID() string {
  26. result := "S"
  27. offset := 0
  28. data := make([]byte, 32)
  29. rand.Read(data)
  30. for len(result) < 16 {
  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[:16]
  39. }
  40. func init() {
  41. store.HandleInit(func(db *mgo.Database) {
  42. collection = db.C("story.stories")
  43. collection.EnsureIndexKey("tags")
  44. collection.EnsureIndexKey("author")
  45. collection.EnsureIndexKey("updatedDate")
  46. collection.EnsureIndexKey("fictionalDate")
  47. collection.EnsureIndexKey("listed")
  48. })
  49. }