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 // 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 }, } }