77 lines
2 KiB
Go
77 lines
2 KiB
Go
package api
|
|
|
|
import (
|
|
"strings"
|
|
|
|
device "github.com/tigorlazuardi/bluemage/go/gen/proto/device/v1"
|
|
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
|
|
"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"
|
|
)
|
|
|
|
func listDevicesRequestSelectStatement(req *device.ListDevicesRequest) SelectStatement {
|
|
cond := Bool(true)
|
|
switch req.Disabled {
|
|
case device.DisabledFilter_DISABLED_FILTER_TRUE:
|
|
cond.AND(Devices.Disabled.EQ(Int(1)))
|
|
case device.DisabledFilter_DISABLED_FILTER_FALSE:
|
|
cond.AND(Devices.Disabled.EQ(Int(0)))
|
|
}
|
|
|
|
if req.Search != "" {
|
|
cond.AND(
|
|
Devices.Name.LIKE(String("%" + req.Search + "%")).
|
|
OR(Devices.Slug.LIKE(String("%" + req.Search + "%"))),
|
|
)
|
|
}
|
|
|
|
stmt := SELECT(Devices.AllColumns).
|
|
FROM(Devices).
|
|
WHERE(cond)
|
|
|
|
if req.Limit > 0 {
|
|
stmt.LIMIT(int64(req.Limit))
|
|
}
|
|
|
|
if req.Offset > 0 {
|
|
stmt.OFFSET(int64(req.Offset))
|
|
}
|
|
|
|
if req.OrderBy == device.OrderBy_ORDER_BY_UNSPECIFIED {
|
|
return stmt.ORDER_BY(Devices.CreatedAt.DESC())
|
|
}
|
|
|
|
orderByField, _ := strings.CutPrefix(device.OrderBy_name[int32(req.OrderBy)], "ORDER_BY_")
|
|
orderByField = strings.ToLower(orderByField)
|
|
|
|
orderBy := StringColumn(orderByField)
|
|
|
|
if req.Sort == device.Sort_SORT_DESCENDING {
|
|
return stmt.ORDER_BY(orderBy.DESC())
|
|
} else {
|
|
return stmt.ORDER_BY(orderBy.ASC())
|
|
}
|
|
}
|
|
|
|
func (api *API) DevicesList(ctx context.Context, req *device.ListDevicesRequest) (resp *device.ListDevicesResponse, err error) {
|
|
ctx, span := tracer.Start(ctx, "DevicesList")
|
|
defer span.End()
|
|
|
|
resp = &device.ListDevicesResponse{}
|
|
stmt := listDevicesRequestSelectStatement(req)
|
|
var out []model.Devices
|
|
if err := stmt.QueryContext(ctx, api.DB, &out); err != nil {
|
|
return resp, errs.Wrapw(err, "failed to list devices",
|
|
"request", req,
|
|
"query", stmt.DebugSql(),
|
|
)
|
|
}
|
|
for _, result := range out {
|
|
resp.Devices = append(resp.Devices, convert.JetModelDeviceToGetDeviceResponse(result))
|
|
}
|
|
return resp, err
|
|
}
|