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.
95 lines
2.4 KiB
95 lines
2.4 KiB
package loaders
|
|
|
|
import (
|
|
"context"
|
|
"git.aiterp.net/rpdata/api/models"
|
|
"git.aiterp.net/rpdata/api/repositories"
|
|
"time"
|
|
)
|
|
|
|
//go:generate go run github.com/vektah/dataloaden CharacterLoader string *git.aiterp.net/rpdata/api/models.Character
|
|
//go:generate go run github.com/vektah/dataloaden ChannelLoader string *git.aiterp.net/rpdata/api/models.Channel
|
|
|
|
// CharacterLoaderFromRepository creates a new CharacterLoader
|
|
func CharacterLoaderFromRepository(repo repositories.CharacterRepository) *CharacterLoader {
|
|
return &CharacterLoader{
|
|
wait: time.Millisecond * 1,
|
|
maxBatch: 100,
|
|
fetch: func(keys []string) ([]*models.Character, []error) {
|
|
timeout, cancel := context.WithTimeout(context.Background(), time.Second*15)
|
|
defer cancel()
|
|
|
|
characters, err := repo.List(timeout, models.CharacterFilter{
|
|
IDs: keys,
|
|
})
|
|
if err != nil {
|
|
errs := make([]error, len(keys))
|
|
for i := range errs {
|
|
errs[i] = err
|
|
}
|
|
|
|
return nil, errs
|
|
}
|
|
|
|
charMap := make(map[string]*models.Character, len(keys))
|
|
for _, character := range characters {
|
|
charMap[character.ID] = character
|
|
}
|
|
|
|
results := make([]*models.Character, len(keys))
|
|
errs := make([]error, len(keys))
|
|
|
|
for i, key := range keys {
|
|
if character, ok := charMap[key]; ok {
|
|
results[i] = character
|
|
} else {
|
|
errs[i] = repositories.ErrNotFound
|
|
}
|
|
}
|
|
|
|
return results, errs
|
|
},
|
|
}
|
|
}
|
|
|
|
// ChannelLoaderFromRepository creates a new CharacterLoader
|
|
func ChannelLoaderFromRepository(repo repositories.ChannelRepository) *ChannelLoader {
|
|
return &ChannelLoader{
|
|
wait: time.Millisecond * 1,
|
|
maxBatch: 100,
|
|
fetch: func(keys []string) ([]*models.Channel, []error) {
|
|
timeout, cancel := context.WithTimeout(context.Background(), time.Second*15)
|
|
defer cancel()
|
|
|
|
channels, err := repo.List(timeout, models.ChannelFilter{
|
|
Names: keys,
|
|
})
|
|
if err != nil {
|
|
errs := make([]error, len(keys))
|
|
for i := range errs {
|
|
errs[i] = err
|
|
}
|
|
|
|
return nil, errs
|
|
}
|
|
|
|
channelMap := make(map[string]*models.Channel, len(keys))
|
|
for _, channel := range channels {
|
|
channelMap[channel.Name] = channel
|
|
}
|
|
|
|
results := make([]*models.Channel, len(keys))
|
|
errs := make([]error, len(keys))
|
|
|
|
for i, key := range keys {
|
|
if channel, ok := channelMap[key]; ok {
|
|
results[i] = channel
|
|
} else {
|
|
errs[i] = repositories.ErrNotFound
|
|
}
|
|
}
|
|
|
|
return results, errs
|
|
},
|
|
}
|
|
}
|