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.

78 lines
1.6 KiB

  1. package loader
  2. import (
  3. "context"
  4. "errors"
  5. "strings"
  6. "git.aiterp.net/rpdata/api/models"
  7. "git.aiterp.net/rpdata/api/models/channels"
  8. "github.com/graph-gophers/dataloader"
  9. )
  10. // Channel gets a character by key
  11. func (loader *Loader) Channel(key, value string) (models.Channel, error) {
  12. if !strings.HasPrefix(key, "Channel.") {
  13. key = "Channel." + key
  14. }
  15. if loader.loaders[key] == nil {
  16. return models.Channel{}, errors.New("unsupported key")
  17. }
  18. loader.loadPrimed(key)
  19. thunk := loader.loaders[key].Load(loader.ctx, dataloader.StringKey(value))
  20. res, err := thunk()
  21. if err != nil {
  22. return models.Channel{}, err
  23. }
  24. channel, ok := res.(models.Channel)
  25. if !ok {
  26. return channel, errors.New("incorrect type")
  27. }
  28. return channel, nil
  29. }
  30. // PrimeChannels primes channels for loading along with the first one.
  31. func (loader *Loader) PrimeChannels(key string, values ...string) {
  32. if !strings.HasPrefix(key, "Channel.") {
  33. key = "Channel." + key
  34. }
  35. loader.prime(key, values)
  36. }
  37. func channelNameBatch(ctx context.Context, keys dataloader.Keys) []*dataloader.Result {
  38. var results []*dataloader.Result
  39. names := keys.Keys()
  40. channels, err := channels.ListNames(names...)
  41. if err != nil {
  42. for range names {
  43. results = append(results, &dataloader.Result{Data: models.Channel{}, Error: err})
  44. }
  45. return results
  46. }
  47. for _, name := range names {
  48. found := false
  49. for i := range channels {
  50. if channels[i].Name == name {
  51. results = append(results, &dataloader.Result{Data: channels[i]})
  52. found = true
  53. break
  54. }
  55. }
  56. if !found {
  57. results = append(results, &dataloader.Result{Data: models.Channel{}, Error: err})
  58. }
  59. }
  60. return results
  61. }