Redmage/api/subreddits_list.go

71 lines
1.8 KiB
Go
Raw Normal View History

2024-04-08 23:18:09 +07:00
package api
import (
"context"
2024-04-24 13:01:13 +07:00
"github.com/stephenafamo/bob"
"github.com/stephenafamo/bob/dialect/sqlite/dialect"
"github.com/stephenafamo/bob/dialect/sqlite/sm"
"github.com/tigorlazuardi/redmage/models"
2024-04-08 23:18:09 +07:00
"github.com/tigorlazuardi/redmage/pkg/errs"
)
type ListSubredditsParams struct {
2024-04-24 13:01:13 +07:00
Name string `json:"name"`
Limit int64 `json:"limit"`
Offset int64 `json:"offset"`
OrderBy string `json:"order_by"`
Sort string `json:"sort"`
}
func (l ListSubredditsParams) Query() (expr []bob.Mod[*dialect.SelectQuery]) {
if l.Name != "" {
expr = append(expr, models.SelectWhere.Subreddits.Name.Like("%"+l.Name+"%"))
}
if l.Limit > 0 {
expr = append(expr, sm.Limit(l.Limit))
}
if l.Offset > 0 {
expr = append(expr, sm.Offset(l.Offset))
}
if l.OrderBy != "" {
if l.Sort == "desc" {
expr = append(expr, sm.OrderBy(l.OrderBy).Desc())
} else {
expr = append(expr, sm.OrderBy(l.OrderBy).Asc())
}
}
return expr
}
func (l ListSubredditsParams) CountQuery() (expr []bob.Mod[*dialect.SelectQuery]) {
if l.Name != "" {
expr = append(expr, models.SelectWhere.Subreddits.Name.Like("%"+l.Name+"%"))
}
return expr
2024-04-08 23:18:09 +07:00
}
type ListSubredditsResult struct {
Total int64
2024-04-24 13:01:13 +07:00
Data models.SubredditSlice
2024-04-08 23:18:09 +07:00
}
func (api *API) ListSubreddits(ctx context.Context, arg ListSubredditsParams) (result ListSubredditsResult, err error) {
2024-04-13 00:15:31 +07:00
ctx, span := tracer.Start(ctx, "api.ListSubreddits")
defer span.End()
2024-04-08 23:18:09 +07:00
2024-04-24 13:01:13 +07:00
result.Data, err = models.Subreddits.Query(ctx, api.exec, arg.Query()...).All()
2024-04-08 23:18:09 +07:00
if err != nil {
2024-04-24 13:01:13 +07:00
return result, errs.Wrapw(err, "failed to list subreddits", "query", arg)
2024-04-08 23:18:09 +07:00
}
2024-04-24 13:01:13 +07:00
result.Total, err = models.Subreddits.Query(ctx, api.exec, arg.CountQuery()...).Count()
2024-04-08 23:18:09 +07:00
if err != nil {
2024-04-24 13:01:13 +07:00
return result, errs.Wrapw(err, "failed to count subreddits", "query", arg)
2024-04-08 23:18:09 +07:00
}
2024-04-24 13:01:13 +07:00
return result, nil
2024-04-08 23:18:09 +07:00
}