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.

66 lines
1.3 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. thunk := loader.loaders[key].Load(loader.ctx, dataloader.StringKey(value))
  18. res, err := thunk()
  19. if err != nil {
  20. return channel.Channel{}, err
  21. }
  22. channel, ok := res.(channel.Channel)
  23. if !ok {
  24. return channel, errors.New("incorrect type")
  25. }
  26. return channel, nil
  27. }
  28. func channelNameBatch(ctx context.Context, keys dataloader.Keys) []*dataloader.Result {
  29. var results []*dataloader.Result
  30. names := keys.Keys()
  31. channels, err := channel.ListNames(names...)
  32. if err != nil {
  33. for range names {
  34. results = append(results, &dataloader.Result{Data: channel.Channel{}, Error: err})
  35. }
  36. return results
  37. }
  38. for _, name := range names {
  39. found := false
  40. for i := range channels {
  41. if channels[i].Name == name {
  42. results = append(results, &dataloader.Result{Data: channels[i]})
  43. found = true
  44. break
  45. }
  46. }
  47. if !found {
  48. results = append(results, &dataloader.Result{Data: channel.Channel{}, Error: err})
  49. }
  50. }
  51. return results
  52. }