2020-06-24 13:25:31 +00:00
|
|
|
package repository
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/go-pg/pg/v10"
|
|
|
|
"github.com/tribalwarshelp/api/tribechange"
|
|
|
|
"github.com/tribalwarshelp/shared/models"
|
|
|
|
)
|
|
|
|
|
|
|
|
type pgRepository struct {
|
|
|
|
*pg.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewPGRepository(db *pg.DB) tribechange.Repository {
|
|
|
|
return &pgRepository{db}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (repo *pgRepository) Fetch(ctx context.Context, cfg tribechange.FetchConfig) ([]*models.TribeChange, int, error) {
|
|
|
|
var err error
|
|
|
|
total := 0
|
|
|
|
data := []*models.TribeChange{}
|
2020-11-21 11:01:16 +00:00
|
|
|
query := repo.
|
|
|
|
WithParam("SERVER", pg.Safe(cfg.Server)).
|
|
|
|
Model(&data).
|
|
|
|
Context(ctx).
|
|
|
|
Limit(cfg.Limit).
|
|
|
|
Offset(cfg.Offset)
|
2021-01-06 16:43:02 +00:00
|
|
|
relationshipAndSortAppender := &models.TribeChangeRelationshipAndSortAppender{
|
|
|
|
Filter: &models.TribeChangeFilter{},
|
|
|
|
Sort: cfg.Sort,
|
2020-06-24 13:25:31 +00:00
|
|
|
}
|
2021-01-06 16:43:02 +00:00
|
|
|
if cfg.Filter != nil {
|
|
|
|
query = query.Apply(cfg.Filter.Where)
|
|
|
|
relationshipAndSortAppender.Filter = cfg.Filter
|
2020-11-21 11:01:16 +00:00
|
|
|
}
|
2021-01-06 16:43:02 +00:00
|
|
|
query = query.Apply(relationshipAndSortAppender.Append)
|
2020-06-24 13:25:31 +00:00
|
|
|
|
2021-03-21 12:03:39 +00:00
|
|
|
if cfg.Count && cfg.Select {
|
2020-06-24 13:25:31 +00:00
|
|
|
total, err = query.SelectAndCount()
|
2021-03-21 12:03:39 +00:00
|
|
|
} else if cfg.Select {
|
2020-06-24 13:25: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:25:31 +00:00
|
|
|
}
|
|
|
|
if err != nil && err != pg.ErrNoRows {
|
|
|
|
if strings.Contains(err.Error(), `relation "`+cfg.Server) {
|
|
|
|
return nil, 0, fmt.Errorf("Server not found")
|
|
|
|
}
|
2021-01-13 19:46:24 +00:00
|
|
|
return nil, 0, fmt.Errorf("Internal server error")
|
2020-06-24 13:25:31 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return data, total, nil
|
|
|
|
}
|