and another one

This commit is contained in:
2026-02-10 18:07:44 +11:00
parent 299c775aba
commit ac5e38d82b
10 changed files with 52 additions and 60 deletions

View File

@@ -9,10 +9,8 @@ import (
)
type listgetter[T any] struct {
q *bun.SelectQuery
items *[]*T
pageOpts *PageOpts
defaults *PageOpts
q *bun.SelectQuery
items *[]*T
}
type List[T any] struct {
@@ -38,17 +36,25 @@ func (f *ListFilter) Add(field string, value any) {
f.filters = append(f.filters, Filter{field, value})
}
func GetList[T any](tx bun.Tx, pageOpts, defaults *PageOpts) *listgetter[T] {
func GetList[T any](tx bun.Tx) *listgetter[T] {
l := &listgetter[T]{
items: new([]*T),
pageOpts: pageOpts,
defaults: defaults,
items: new([]*T),
}
l.q = tx.NewSelect().
Model(l.items)
return l
}
func (l *listgetter[T]) Join(join string, args ...any) *listgetter[T] {
l.q = l.q.Join(join, args...)
return l
}
func (l *listgetter[T]) Where(query string, args ...any) *listgetter[T] {
l.q = l.q.Where(query, args...)
return l
}
func (l *listgetter[T]) Relation(name string, apply ...func(*bun.SelectQuery) *bun.SelectQuery) *listgetter[T] {
l.q = l.q.Relation(name, apply...)
return l
@@ -61,15 +67,15 @@ func (l *listgetter[T]) Filter(filters ...Filter) *listgetter[T] {
return l
}
func (l *listgetter[T]) GetAll(ctx context.Context) (*List[T], error) {
if l.defaults == nil {
func (l *listgetter[T]) GetPaged(ctx context.Context, pageOpts, defaults *PageOpts) (*List[T], error) {
if defaults == nil {
return nil, errors.New("default pageopts is nil")
}
total, err := l.q.Count(ctx)
if err != nil {
return nil, errors.Wrap(err, "query.Count")
}
l.q, l.pageOpts = setPageOpts(l.q, l.pageOpts, l.defaults, total)
l.q, pageOpts = setPageOpts(l.q, pageOpts, defaults, total)
err = l.q.Scan(ctx)
if err != nil && errors.Is(err, sql.ErrNoRows) {
return nil, errors.Wrap(err, "query.Scan")
@@ -77,7 +83,15 @@ func (l *listgetter[T]) GetAll(ctx context.Context) (*List[T], error) {
list := &List[T]{
Items: *l.items,
Total: total,
PageOpts: *l.pageOpts,
PageOpts: *pageOpts,
}
return list, nil
}
func (l *listgetter[T]) GetAll(ctx context.Context) ([]*T, error) {
err := l.q.Scan(ctx)
if err != nil && errors.Is(err, sql.ErrNoRows) {
return nil, errors.Wrap(err, "query.Scan")
}
return *l.items, nil
}