This repository has been archived on 2024-04-06. You can view files and clone it, but cannot push or open issues or pull requests.
core-old/internal/service/player_snapshot.go
Dawid Wysokiński 6c8b30d061
All checks were successful
continuous-integration/drone/push Build is passing
refactor: player - split the List method into two (#144)
Reviewed-on: twhelp/core#144
2022-12-23 07:56:31 +00:00

81 lines
2.1 KiB
Go

package service
import (
"context"
"fmt"
"time"
"gitea.dwysokinski.me/twhelp/core/internal/domain"
)
//counterfeiter:generate -o internal/mock/player_lister.gen.go . PlayerLister
type PlayerLister interface {
List(ctx context.Context, params domain.ListPlayersParams) ([]domain.Player, error)
}
//counterfeiter:generate -o internal/mock/player_snapshot_repository.gen.go . PlayerSnapshotRepository
type PlayerSnapshotRepository interface {
Create(ctx context.Context, params ...domain.CreatePlayerSnapshotParams) error
}
type PlayerSnapshot struct {
repo PlayerSnapshotRepository
playerSvc PlayerLister
}
func NewPlayerSnapshot(repo PlayerSnapshotRepository, playerSvc PlayerLister) *PlayerSnapshot {
return &PlayerSnapshot{repo: repo, playerSvc: playerSvc}
}
func (p *PlayerSnapshot) Create(ctx context.Context, key string, date time.Time) error {
var lastID int64
for {
players, err := p.playerSvc.List(ctx, domain.ListPlayersParams{
ServerKeys: []string{key},
IDGT: domain.NullInt64{
Int64: lastID,
Valid: true,
},
Deleted: domain.NullBool{
Valid: true,
Bool: false,
},
Pagination: domain.Pagination{
Limit: playerMaxLimit,
},
Sort: []domain.PlayerSort{
{By: domain.PlayerSortByID, Direction: domain.SortDirectionASC},
},
})
if err != nil {
return fmt.Errorf("PlayerRepository.List: %w", err)
}
params := make([]domain.CreatePlayerSnapshotParams, 0, len(players))
for _, player := range players {
params = append(params, domain.CreatePlayerSnapshotParams{
OpponentsDefeated: player.OpponentsDefeated,
PlayerID: player.ID,
NumVillages: player.NumVillages,
Points: player.Points,
Rank: player.Rank,
TribeID: player.TribeID,
ServerKey: player.ServerKey,
Date: date,
})
}
if err = p.repo.Create(ctx, params...); err != nil {
return fmt.Errorf("PlayerSnapshotRepository.Create: %w", err)
}
if len(players) < playerMaxLimit {
break
}
lastID = players[len(players)-1].ID
}
return nil
}