2020-06-02 15:45:21 +00:00
|
|
|
package usecase
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
2020-12-25 11:07:54 +00:00
|
|
|
"strings"
|
2020-06-02 15:45:21 +00:00
|
|
|
|
2020-08-09 12:32:46 +00:00
|
|
|
"github.com/tribalwarshelp/api/middleware"
|
2020-06-02 15:45:21 +00:00
|
|
|
"github.com/tribalwarshelp/api/player"
|
2020-06-04 13:06:32 +00:00
|
|
|
"github.com/tribalwarshelp/api/utils"
|
2020-06-02 15:45:21 +00:00
|
|
|
"github.com/tribalwarshelp/shared/models"
|
|
|
|
)
|
|
|
|
|
|
|
|
type usecase struct {
|
|
|
|
repo player.Repository
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(repo player.Repository) player.Usecase {
|
|
|
|
return &usecase{repo}
|
|
|
|
}
|
|
|
|
|
2020-11-21 09:08:22 +00:00
|
|
|
func (ucase *usecase) Fetch(ctx context.Context, cfg player.FetchConfig) ([]*models.Player, int, error) {
|
|
|
|
if cfg.Filter == nil {
|
|
|
|
cfg.Filter = &models.PlayerFilter{}
|
2020-06-02 15:45:21 +00:00
|
|
|
}
|
2020-11-21 09:08:22 +00:00
|
|
|
|
2021-03-21 06:42:12 +00:00
|
|
|
if !middleware.CanExceedLimit(ctx) && (cfg.Limit > player.FetchLimit || cfg.Limit <= 0) {
|
|
|
|
cfg.Limit = player.FetchLimit
|
2020-11-21 09:08:22 +00:00
|
|
|
}
|
2021-03-20 17:13:45 +00:00
|
|
|
cfg.Sort = utils.SanitizeSorts(cfg.Sort)
|
2020-11-21 09:08:22 +00:00
|
|
|
return ucase.repo.Fetch(ctx, cfg)
|
2020-06-02 15:45:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ucase *usecase) GetByID(ctx context.Context, server string, id int) (*models.Player, error) {
|
2020-06-24 13:05:31 +00:00
|
|
|
players, _, err := ucase.repo.Fetch(ctx, player.FetchConfig{
|
|
|
|
Server: server,
|
|
|
|
Filter: &models.PlayerFilter{
|
2020-11-21 09:08:22 +00:00
|
|
|
ID: []int{id},
|
2020-06-24 13:05:31 +00:00
|
|
|
},
|
2020-11-21 09:08:22 +00:00
|
|
|
Limit: 1,
|
|
|
|
Count: false,
|
2020-06-02 15:45:21 +00:00
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2020-06-24 13:05:31 +00:00
|
|
|
if len(players) == 0 {
|
2020-06-18 11:06:55 +00:00
|
|
|
return nil, fmt.Errorf("Player (ID: %d) not found.", id)
|
2020-06-02 15:45:21 +00:00
|
|
|
}
|
|
|
|
return players[0], nil
|
|
|
|
}
|
2020-12-25 11:07:54 +00:00
|
|
|
|
|
|
|
func (ucase *usecase) SearchPlayer(ctx context.Context, cfg player.SearchPlayerConfig) ([]*models.FoundPlayer, int, error) {
|
|
|
|
if "" == strings.TrimSpace(cfg.Version) {
|
|
|
|
return nil, 0, fmt.Errorf("Version is required.")
|
|
|
|
}
|
|
|
|
if "" == strings.TrimSpace(cfg.Name) && cfg.ID <= 0 {
|
|
|
|
return nil, 0, fmt.Errorf("Your search is ambiguous. You must specify the variable 'name' or 'id'.")
|
|
|
|
}
|
2021-03-21 06:42:12 +00:00
|
|
|
if !middleware.CanExceedLimit(ctx) && (cfg.Limit > player.FetchLimit || cfg.Limit <= 0) {
|
|
|
|
cfg.Limit = player.FetchLimit
|
2020-12-25 11:07:54 +00:00
|
|
|
}
|
2021-03-20 17:13:45 +00:00
|
|
|
cfg.Sort = utils.SanitizeSorts(cfg.Sort)
|
2020-12-25 11:07:54 +00:00
|
|
|
return ucase.repo.SearchPlayer(ctx, cfg)
|
|
|
|
}
|