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
78 lines
1.6 KiB
package loader
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
|
|
"git.aiterp.net/rpdata/api/models"
|
|
"git.aiterp.net/rpdata/api/models/channels"
|
|
"github.com/graph-gophers/dataloader"
|
|
)
|
|
|
|
// Channel gets a character by key
|
|
func (loader *Loader) Channel(key, value string) (models.Channel, error) {
|
|
if !strings.HasPrefix(key, "Channel.") {
|
|
key = "Channel." + key
|
|
}
|
|
|
|
if loader.loaders[key] == nil {
|
|
return models.Channel{}, errors.New("unsupported key")
|
|
}
|
|
|
|
loader.loadPrimed(key)
|
|
|
|
thunk := loader.loaders[key].Load(loader.ctx, dataloader.StringKey(value))
|
|
res, err := thunk()
|
|
if err != nil {
|
|
return models.Channel{}, err
|
|
}
|
|
|
|
channel, ok := res.(models.Channel)
|
|
if !ok {
|
|
return channel, errors.New("incorrect type")
|
|
}
|
|
|
|
return channel, nil
|
|
}
|
|
|
|
// PrimeChannels primes channels for loading along with the first one.
|
|
func (loader *Loader) PrimeChannels(key string, values ...string) {
|
|
if !strings.HasPrefix(key, "Channel.") {
|
|
key = "Channel." + key
|
|
}
|
|
|
|
loader.prime(key, values)
|
|
}
|
|
|
|
func channelNameBatch(ctx context.Context, keys dataloader.Keys) []*dataloader.Result {
|
|
var results []*dataloader.Result
|
|
names := keys.Keys()
|
|
|
|
channels, err := channels.ListNames(names...)
|
|
if err != nil {
|
|
for range names {
|
|
results = append(results, &dataloader.Result{Data: models.Channel{}, Error: err})
|
|
}
|
|
|
|
return results
|
|
}
|
|
|
|
for _, name := range names {
|
|
found := false
|
|
for i := range channels {
|
|
if channels[i].Name == name {
|
|
results = append(results, &dataloader.Result{Data: channels[i]})
|
|
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
|
|
if !found {
|
|
results = append(results, &dataloader.Result{Data: models.Channel{}, Error: err})
|
|
}
|
|
}
|
|
|
|
return results
|
|
}
|