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.

53 lines
1.3 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. // CharacterLoaderFromRepository creates a new CharacterLoader
  10. func CharacterLoaderFromRepository(repo repositories.CharacterRepository) *CharacterLoader {
  11. return &CharacterLoader{
  12. wait: time.Millisecond * 1,
  13. maxBatch: 100,
  14. fetch: func(keys []string) ([]*models.Character, []error) {
  15. timeout, cancel := context.WithTimeout(context.Background(), time.Second*15)
  16. defer cancel()
  17. characters, err := repo.List(timeout, models.CharacterFilter{
  18. IDs: keys,
  19. })
  20. if err != nil {
  21. errs := make([]error, len(keys))
  22. for i := range errs {
  23. errs[i] = err
  24. }
  25. return nil, errs
  26. }
  27. charMap := make(map[string]*models.Character, len(keys))
  28. for _, character := range characters {
  29. charMap[character.ID] = character
  30. }
  31. results := make([]*models.Character, len(keys))
  32. errs := make([]error, len(keys))
  33. for i, key := range keys {
  34. if character, ok := charMap[key]; ok {
  35. results[i] = character
  36. } else {
  37. errs[i] = repositories.ErrNotFound
  38. }
  39. }
  40. return results, errs
  41. },
  42. }
  43. }