70 lines
1.7 KiB
Go
70 lines
1.7 KiB
Go
package bundb
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/bundb/internal/model"
|
|
"gitea.dwysokinski.me/twhelp/dcbot/internal/domain"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
type Group struct {
|
|
db *bun.DB
|
|
}
|
|
|
|
func NewGroup(db *bun.DB) *Group {
|
|
return &Group{db: db}
|
|
}
|
|
|
|
func (g *Group) Create(ctx context.Context, params domain.CreateGroupParams) (domain.Group, error) {
|
|
group := model.Group{
|
|
ServerID: params.ServerID(),
|
|
VersionCode: params.VersionCode(),
|
|
ChannelGainedVillages: params.ChannelGainedVillages(),
|
|
ChannelLostVillages: params.ChannelLostVillages(),
|
|
ServerKey: params.ServerKey(),
|
|
}
|
|
|
|
if _, err := g.db.NewInsert().
|
|
Model(&group).
|
|
Returning("*").
|
|
Exec(ctx); err != nil {
|
|
return domain.Group{}, fmt.Errorf("something went wrong while inserting group into the db: %w", err)
|
|
}
|
|
|
|
return group.ToDomain(), nil
|
|
}
|
|
|
|
func (g *Group) List(ctx context.Context, params domain.ListGroupsParams) ([]domain.Group, error) {
|
|
var groups []model.Group
|
|
|
|
if err := g.db.NewSelect().
|
|
Model(&groups).
|
|
Order("created_at ASC").
|
|
Apply(listGroupsParamsApplier{params}.apply).
|
|
Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return nil, fmt.Errorf("couldn't select groups from the db: %w", err)
|
|
}
|
|
|
|
result := make([]domain.Group, 0, len(groups))
|
|
for _, version := range groups {
|
|
result = append(result, version.ToDomain())
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
type listGroupsParamsApplier struct {
|
|
params domain.ListGroupsParams
|
|
}
|
|
|
|
func (l listGroupsParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery {
|
|
if l.params.ServerIDs != nil {
|
|
q = q.Where("server_id IN (?)", bun.In(l.params.ServerIDs))
|
|
}
|
|
|
|
return q
|
|
}
|