This repository has been archived on 2022-09-04. You can view files and clone it, but cannot push or open issues or pull requests.
api/tribehistory/repository/pg_repository.go

48 lines
1022 B
Go

package repository
import (
"context"
"fmt"
"strings"
"github.com/go-pg/pg/v10"
"github.com/pkg/errors"
"github.com/tribalwarshelp/api/tribehistory"
"github.com/tribalwarshelp/shared/models"
)
type pgRepository struct {
*pg.DB
}
func NewPGRepository(db *pg.DB) tribehistory.Repository {
return &pgRepository{db}
}
func (repo *pgRepository) Fetch(ctx context.Context, server string, f *models.TribeHistoryFilter) ([]*models.TribeHistory, int, error) {
var err error
data := []*models.TribeHistory{}
query := repo.WithParam("SERVER", pg.Safe(server)).Model(&data).Context(ctx)
if f != nil {
query = query.
WhereStruct(f).
Limit(f.Limit).
Offset(f.Offset)
if f.Sort != "" {
query = query.Order(f.Sort)
}
}
total, err := query.SelectAndCount()
if err != nil && err != pg.ErrNoRows {
if strings.Contains(err.Error(), `relation "`+server) {
return nil, 0, fmt.Errorf("Server not found")
}
return nil, 0, errors.Wrap(err, "Internal server error")
}
return data, total, nil
}