77 lines
1.7 KiB
Go
77 lines
1.7 KiB
Go
|
package api
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
|
||
|
"github.com/tigorlazuardi/bluemage/go/gen/jet/model"
|
||
|
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
|
||
|
"github.com/tigorlazuardi/bluemage/go/pkg/telemetry"
|
||
|
|
||
|
. "github.com/go-jet/jet/v2/sqlite"
|
||
|
. "github.com/tigorlazuardi/bluemage/go/gen/jet/table"
|
||
|
)
|
||
|
|
||
|
type ListSubredditsRequest struct {
|
||
|
Search string
|
||
|
Disabled *bool
|
||
|
Limit int64
|
||
|
Offset int64
|
||
|
OrderBy string
|
||
|
Sort Sort
|
||
|
}
|
||
|
|
||
|
func (request ListSubredditsRequest) Statement() SelectStatement {
|
||
|
cond := Bool(true)
|
||
|
|
||
|
if request.Search != "" {
|
||
|
cond.AND(Subreddits.Name.LIKE(String("%" + request.Search + "%")))
|
||
|
}
|
||
|
if request.Disabled != nil {
|
||
|
b := *request.Disabled
|
||
|
if b {
|
||
|
cond.AND(Subreddits.Disabled.EQ(Int(1)))
|
||
|
} else {
|
||
|
cond.AND(Subreddits.Disabled.EQ(Int(0)))
|
||
|
}
|
||
|
}
|
||
|
|
||
|
stmt := SELECT(Subreddits.AllColumns).WHERE(cond)
|
||
|
|
||
|
if request.Limit > 0 {
|
||
|
stmt.LIMIT(request.Limit)
|
||
|
}
|
||
|
|
||
|
if request.Offset > 0 {
|
||
|
stmt.OFFSET(request.Offset)
|
||
|
}
|
||
|
|
||
|
if request.OrderBy == "" {
|
||
|
return stmt.ORDER_BY(Subreddits.UpdatedAt.DESC())
|
||
|
}
|
||
|
|
||
|
orderBy := StringColumn(request.OrderBy)
|
||
|
if request.Sort == SortDesc {
|
||
|
return stmt.ORDER_BY(orderBy.DESC())
|
||
|
} else {
|
||
|
return stmt.ORDER_BY(orderBy.ASC())
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (api *API) ListSubreddits(ctx context.Context, request ListSubredditsRequest) (subreddits []model.Subreddits, err error) {
|
||
|
ctx, span := tracer.Start(ctx, "ListSubreddits")
|
||
|
defer func() { telemetry.EndWithStatus(span, err) }()
|
||
|
|
||
|
stmt := request.Statement()
|
||
|
err = stmt.QueryContext(ctx, api.DB, &subreddits)
|
||
|
if err != nil {
|
||
|
err = errs.Wrapw(
|
||
|
err, "failed to list subreddits",
|
||
|
"request", request,
|
||
|
"query", stmt.DebugSql(),
|
||
|
)
|
||
|
return subreddits, err
|
||
|
}
|
||
|
|
||
|
return subreddits, nil
|
||
|
}
|