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/tribe_snapshot.go
Dawid Wysokiński 1f41f66287
All checks were successful
continuous-integration/drone/push Build is passing
refactor: tribe - split the List method into two (#142)
Reviewed-on: twhelp/core#142
2022-12-22 08:06:35 +00:00

83 lines
2.1 KiB
Go

package service
import (
"context"
"fmt"
"time"
"gitea.dwysokinski.me/twhelp/core/internal/domain"
)
//counterfeiter:generate -o internal/mock/tribe_lister.gen.go . TribeLister
type TribeLister interface {
List(ctx context.Context, params domain.ListTribesParams) ([]domain.Tribe, error)
}
//counterfeiter:generate -o internal/mock/tribe_snapshot_repository.gen.go . TribeSnapshotRepository
type TribeSnapshotRepository interface {
Create(ctx context.Context, params ...domain.CreateTribeSnapshotParams) error
}
type TribeSnapshot struct {
repo TribeSnapshotRepository
tribeSvc TribeLister
}
func NewTribeSnapshot(repo TribeSnapshotRepository, tribeSvc TribeLister) *TribeSnapshot {
return &TribeSnapshot{repo: repo, tribeSvc: tribeSvc}
}
func (t *TribeSnapshot) Create(ctx context.Context, key string, date time.Time) error {
var lastID int64
for {
tribes, err := t.tribeSvc.List(ctx, domain.ListTribesParams{
ServerKeys: []string{key},
IDGT: domain.NullInt64{
Int64: lastID,
Valid: true,
},
Deleted: domain.NullBool{
Valid: true,
Bool: false,
},
Pagination: domain.Pagination{
Limit: tribeMaxLimit,
},
Sort: []domain.TribeSort{
{By: domain.TribeSortByID, Direction: domain.SortDirectionASC},
},
})
if err != nil {
return fmt.Errorf("TribeRepository.List: %w", err)
}
params := make([]domain.CreateTribeSnapshotParams, 0, len(tribes))
for _, tribe := range tribes {
params = append(params, domain.CreateTribeSnapshotParams{
OpponentsDefeated: tribe.OpponentsDefeated,
TribeID: tribe.ID,
ServerKey: tribe.ServerKey,
NumMembers: tribe.NumMembers,
NumVillages: tribe.NumVillages,
Points: tribe.Points,
AllPoints: tribe.AllPoints,
Rank: tribe.Rank,
Dominance: tribe.Dominance,
Date: date,
})
}
if err = t.repo.Create(ctx, params...); err != nil {
return fmt.Errorf("TribeSnapshotRepository.Create: %w", err)
}
if len(tribes) < tribeMaxLimit {
break
}
lastID = tribes[len(tribes)-1].ID
}
return nil
}