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.

95 lines
2.4 KiB

  1. package loaders
  2. import (
  3. "context"
  4. "git.aiterp.net/rpdata/api/models"
  5. "git.aiterp.net/rpdata/api/repositories"
  6. "time"
  7. )
  8. //go:generate go run github.com/vektah/dataloaden CharacterLoader string *git.aiterp.net/rpdata/api/models.Character
  9. //go:generate go run github.com/vektah/dataloaden ChannelLoader string *git.aiterp.net/rpdata/api/models.Channel
  10. // CharacterLoaderFromRepository creates a new CharacterLoader
  11. func CharacterLoaderFromRepository(repo repositories.CharacterRepository) *CharacterLoader {
  12. return &CharacterLoader{
  13. wait: time.Millisecond * 1,
  14. maxBatch: 100,
  15. fetch: func(keys []string) ([]*models.Character, []error) {
  16. timeout, cancel := context.WithTimeout(context.Background(), time.Second*15)
  17. defer cancel()
  18. characters, err := repo.List(timeout, models.CharacterFilter{
  19. IDs: keys,
  20. })
  21. if err != nil {
  22. errs := make([]error, len(keys))
  23. for i := range errs {
  24. errs[i] = err
  25. }
  26. return nil, errs
  27. }
  28. charMap := make(map[string]*models.Character, len(keys))
  29. for _, character := range characters {
  30. charMap[character.ID] = character
  31. }
  32. results := make([]*models.Character, len(keys))
  33. errs := make([]error, len(keys))
  34. for i, key := range keys {
  35. if character, ok := charMap[key]; ok {
  36. results[i] = character
  37. } else {
  38. errs[i] = repositories.ErrNotFound
  39. }
  40. }
  41. return results, errs
  42. },
  43. }
  44. }
  45. // ChannelLoaderFromRepository creates a new CharacterLoader
  46. func ChannelLoaderFromRepository(repo repositories.ChannelRepository) *ChannelLoader {
  47. return &ChannelLoader{
  48. wait: time.Millisecond * 1,
  49. maxBatch: 100,
  50. fetch: func(keys []string) ([]*models.Channel, []error) {
  51. timeout, cancel := context.WithTimeout(context.Background(), time.Second*15)
  52. defer cancel()
  53. channels, err := repo.List(timeout, models.ChannelFilter{
  54. Names: keys,
  55. })
  56. if err != nil {
  57. errs := make([]error, len(keys))
  58. for i := range errs {
  59. errs[i] = err
  60. }
  61. return nil, errs
  62. }
  63. channelMap := make(map[string]*models.Channel, len(keys))
  64. for _, channel := range channels {
  65. channelMap[channel.Name] = channel
  66. }
  67. results := make([]*models.Channel, len(keys))
  68. errs := make([]error, len(keys))
  69. for i, key := range keys {
  70. if channel, ok := channelMap[key]; ok {
  71. results[i] = channel
  72. } else {
  73. errs[i] = repositories.ErrNotFound
  74. }
  75. }
  76. return results, errs
  77. },
  78. }
  79. }