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.

77 lines
1.6 KiB

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