Bluemage/go/api/devices_list.go

76 lines
1.7 KiB
Go

package api
import (
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
"github.com/tigorlazuardi/bluemage/go/pkg/telemetry"
"golang.org/x/net/context"
. "github.com/go-jet/jet/v2/sqlite"
"github.com/tigorlazuardi/bluemage/go/gen/jet/model"
. "github.com/tigorlazuardi/bluemage/go/gen/jet/table"
)
type ListDevicesRequest struct {
Search string
Disabled *bool
Limit int64
Offset int64
OrderBy string
Sort Sort
}
func (request ListDevicesRequest) Statement() SelectStatement {
cond := Bool(true)
if d := request.Disabled; d != nil {
disabled := *d
if disabled {
cond.AND(Devices.Disabled.EQ(Int(1)))
} else {
cond.AND(Devices.Disabled.EQ(Int(0)))
}
}
if request.Search != "" {
cond.AND(
Devices.Name.LIKE(String("%" + request.Search + "%")).
OR(Devices.Slug.LIKE(String("%" + request.Search + "%"))),
)
}
stmt := SELECT(Devices.AllColumns).
FROM(Devices).
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(Devices.CreatedAt.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) DevicesList(ctx context.Context, req ListDevicesRequest) (resp []model.Devices, err error) {
ctx, span := tracer.Start(ctx, "DevicesList")
defer func() { telemetry.EndWithStatus(span, err) }()
stmt := req.Statement()
if err := stmt.QueryContext(ctx, api.DB, &resp); err != nil {
return resp, errs.Wrapw(err, "failed to list devices",
"request", req,
"query", stmt.DebugSql(),
)
}
return resp, err
}