2020-06-21 11:51:26 +00:00
|
|
|
package repository
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-05-05 17:32:45 +00:00
|
|
|
"github.com/Kichiyaki/gopgutil/v10"
|
2021-05-05 17:49:00 +00:00
|
|
|
"github.com/pkg/errors"
|
2021-05-05 17:32:45 +00:00
|
|
|
"github.com/tribalwarshelp/shared/tw/twmodel"
|
2020-06-21 11:51:26 +00:00
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/go-pg/pg/v10"
|
2021-05-05 17:32:45 +00:00
|
|
|
|
2020-06-21 11:51:26 +00:00
|
|
|
"github.com/tribalwarshelp/api/serverstats"
|
|
|
|
)
|
|
|
|
|
|
|
|
type pgRepository struct {
|
|
|
|
*pg.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPGRepository(db *pg.DB) serverstats.Repository {
|
|
|
|
return &pgRepository{db}
|
|
|
|
}
|
|
|
|
|
2021-05-05 17:32:45 +00:00
|
|
|
func (repo *pgRepository) Fetch(ctx context.Context, cfg serverstats.FetchConfig) ([]*twmodel.ServerStats, int, error) {
|
2020-06-21 11:51:26 +00:00
|
|
|
var err error
|
2021-05-05 17:58:45 +00:00
|
|
|
var data []*twmodel.ServerStats
|
2020-06-24 13:05:31 +00:00
|
|
|
total := 0
|
2020-11-21 11:01:16 +00:00
|
|
|
query := repo.
|
|
|
|
WithParam("SERVER", pg.Safe(cfg.Server)).
|
|
|
|
Model(&data).
|
|
|
|
Context(ctx).
|
|
|
|
Limit(cfg.Limit).
|
2021-05-05 17:32:45 +00:00
|
|
|
Offset(cfg.Offset).
|
|
|
|
Apply(cfg.Filter.Where).
|
|
|
|
Apply(gopgutil.OrderAppender{
|
|
|
|
Orders: cfg.Sort,
|
|
|
|
MaxDepth: 4,
|
|
|
|
}.Apply)
|
2020-06-21 11:51:26 +00:00
|
|
|
|
2021-03-21 12:03:39 +00:00
|
|
|
if cfg.Count && cfg.Select {
|
2020-06-24 13:05:31 +00:00
|
|
|
total, err = query.SelectAndCount()
|
2021-03-21 12:03:39 +00:00
|
|
|
} else if cfg.Select {
|
2020-06-24 13:05:31 +00:00
|
|
|
err = query.Select()
|
2021-03-21 12:03:39 +00:00
|
|
|
} else if cfg.Count {
|
|
|
|
total, err = query.Count()
|
2020-06-24 13:05:31 +00:00
|
|
|
}
|
2020-06-21 11:51:26 +00:00
|
|
|
if err != nil && err != pg.ErrNoRows {
|
2020-06-24 13:05:31 +00:00
|
|
|
if strings.Contains(err.Error(), `relation "`+cfg.Server) {
|
2021-05-05 17:49:00 +00:00
|
|
|
return nil, 0, errors.New("Server not found")
|
2020-06-21 11:51:26 +00:00
|
|
|
}
|
2021-05-05 17:49:00 +00:00
|
|
|
return nil, 0, errors.New("Internal server error")
|
2020-06-21 11:51:26 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return data, total, nil
|
|
|
|
}
|