Bluemage/go/api/devices_count.go

40 lines
1.3 KiB
Go

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/bluemage/go/gen/models"
device "github.com/tigorlazuardi/bluemage/go/gen/proto/device/v1"
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
)
func queryFromCountDevicesRequest(req *device.CountDevicesRequest) (expr []bob.Mod[*dialect.SelectQuery]) {
switch req.Disabled {
case device.DisabledFilter_DISABLED_FILTER_TRUE:
expr = append(expr, models.SelectWhere.Devices.Disabled.EQ(1))
case device.DisabledFilter_DISABLED_FILTER_FALSE:
expr = append(expr, models.SelectWhere.Devices.Disabled.EQ(0))
}
if req.Search != "" {
arg := sqlite.Arg("%" + req.Search + "%")
expr = append(expr,
sm.Where(
models.DeviceColumns.Name.Like(arg).Or(models.DeviceColumns.Slug.Like(arg)),
),
)
}
return expr
}
func (api *API) DevicesCount(ctx context.Context, request *device.CountDevicesRequest) (uint64, error) {
count, err := models.Devices.Query(ctx, api.DB, queryFromCountDevicesRequest(request)...).Count()
if err != nil {
return 0, errs.Wrapw(err, "failed to count devices", "request", request)
}
return uint64(count), nil
}