Redmage/api/devices_list.go

92 lines
2 KiB
Go
Raw Normal View History

2024-04-14 17:30:04 +07:00
package api
import (
"context"
"github.com/stephenafamo/bob"
"github.com/stephenafamo/bob/dialect/sqlite"
"github.com/stephenafamo/bob/dialect/sqlite/dialect"
"github.com/stephenafamo/bob/dialect/sqlite/sm"
"github.com/tigorlazuardi/redmage/models"
2024-04-14 17:30:04 +07:00
"github.com/tigorlazuardi/redmage/pkg/errs"
)
type DevicesListParams struct {
All bool
Q string
Limit int64
Offset int64
OrderBy string
Sort string
2024-04-26 22:13:04 +07:00
Active bool
2024-04-14 17:30:04 +07:00
}
func (dlp DevicesListParams) Query() (expr []bob.Mod[*dialect.SelectQuery]) {
expr = append(expr, dlp.CountQuery()...)
2024-04-26 22:13:04 +07:00
if dlp.Active {
expr = append(expr, models.SelectWhere.Devices.Enable.EQ(1))
}
if dlp.All {
return expr
}
2024-04-14 17:30:04 +07:00
if dlp.Limit > 0 {
expr = append(expr, sm.Limit(dlp.Limit))
}
2024-04-14 17:30:04 +07:00
if dlp.Offset > 0 {
expr = append(expr, sm.Offset(dlp.Offset))
}
2024-04-14 17:30:04 +07:00
if dlp.OrderBy != "" {
order := sm.OrderBy(sqlite.Quote(dlp.OrderBy))
if dlp.Sort == "desc" {
expr = append(expr, order.Desc())
} else {
expr = append(expr, order.Asc())
2024-04-14 17:30:04 +07:00
}
}
return expr
}
func (dlp DevicesListParams) CountQuery() (expr []bob.Mod[*dialect.SelectQuery]) {
2024-04-26 22:13:04 +07:00
if dlp.Active {
expr = append(expr, models.SelectWhere.Devices.Enable.EQ(1))
}
if dlp.Q != "" {
arg := sqlite.Arg("%" + dlp.Q + "%")
expr = append(expr,
sm.Where(
models.DeviceColumns.Name.Like(arg).Or(models.DeviceColumns.Slug.Like(arg)),
),
)
2024-04-14 17:30:04 +07:00
}
return expr
}
type DevicesListResult struct {
Devices models.DeviceSlice `json:"devices"`
Total int64 `json:"total"`
}
func (api *API) DevicesList(ctx context.Context, params DevicesListParams) (result DevicesListResult, err error) {
ctx, span := tracer.Start(ctx, "*API.DevicesList")
defer span.End()
2024-04-25 13:28:35 +07:00
result.Devices, err = models.Devices.Query(ctx, api.db, params.Query()...).All()
2024-04-14 17:30:04 +07:00
if err != nil {
return result, errs.Wrapw(err, "failed to query devices", "params", params)
2024-04-14 17:30:04 +07:00
}
2024-04-25 13:28:35 +07:00
result.Total, err = models.Devices.Query(ctx, api.db, params.CountQuery()...).Count()
2024-04-14 17:30:04 +07:00
if err != nil {
return result, errs.Wrapw(err, "failed to count devices", "params", params)
2024-04-14 17:30:04 +07:00
}
return result, nil
}