2024-08-07 23:59:29 +07:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/tigorlazuardi/bluemage/go/pkg/errs"
|
|
|
|
"golang.org/x/net/context"
|
2024-08-15 09:36:06 +07:00
|
|
|
|
|
|
|
. "github.com/go-jet/jet/v2/sqlite"
|
|
|
|
"github.com/tigorlazuardi/bluemage/go/gen/jet/model"
|
|
|
|
. "github.com/tigorlazuardi/bluemage/go/gen/jet/table"
|
2024-08-07 23:59:29 +07:00
|
|
|
)
|
|
|
|
|
2024-08-15 10:23:56 +07:00
|
|
|
type ListDevicesRequest struct {
|
|
|
|
Search string
|
|
|
|
Disabled *bool
|
|
|
|
Limit int64
|
|
|
|
Offset int64
|
|
|
|
OrderBy string
|
|
|
|
Sort Sort
|
|
|
|
}
|
|
|
|
|
|
|
|
func (request ListDevicesRequest) Statement() SelectStatement {
|
2024-08-15 09:36:06 +07:00
|
|
|
cond := Bool(true)
|
2024-08-15 10:23:56 +07:00
|
|
|
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)))
|
|
|
|
}
|
2024-08-08 22:51:53 +07:00
|
|
|
}
|
|
|
|
|
2024-08-15 10:23:56 +07:00
|
|
|
if request.Search != "" {
|
2024-08-15 09:36:06 +07:00
|
|
|
cond.AND(
|
2024-08-15 10:23:56 +07:00
|
|
|
Devices.Name.LIKE(String("%" + request.Search + "%")).
|
|
|
|
OR(Devices.Slug.LIKE(String("%" + request.Search + "%"))),
|
2024-08-08 22:51:53 +07:00
|
|
|
)
|
|
|
|
}
|
2024-08-07 23:59:29 +07:00
|
|
|
|
2024-08-15 09:36:06 +07:00
|
|
|
stmt := SELECT(Devices.AllColumns).
|
|
|
|
FROM(Devices).
|
|
|
|
WHERE(cond)
|
|
|
|
|
2024-08-15 10:23:56 +07:00
|
|
|
if request.Limit > 0 {
|
|
|
|
stmt.LIMIT(request.Limit)
|
2024-08-07 23:59:29 +07:00
|
|
|
}
|
|
|
|
|
2024-08-15 10:23:56 +07:00
|
|
|
if request.Offset > 0 {
|
|
|
|
stmt.OFFSET(request.Offset)
|
2024-08-07 23:59:29 +07:00
|
|
|
}
|
2024-08-15 10:23:56 +07:00
|
|
|
if request.OrderBy == "" {
|
2024-08-15 09:36:06 +07:00
|
|
|
return stmt.ORDER_BY(Devices.CreatedAt.DESC())
|
2024-08-07 23:59:29 +07:00
|
|
|
}
|
|
|
|
|
2024-08-15 10:23:56 +07:00
|
|
|
orderBy := StringColumn(request.OrderBy)
|
|
|
|
if request.Sort == SortDesc {
|
2024-08-15 09:36:06 +07:00
|
|
|
return stmt.ORDER_BY(orderBy.DESC())
|
2024-08-07 23:59:29 +07:00
|
|
|
} else {
|
2024-08-15 09:36:06 +07:00
|
|
|
return stmt.ORDER_BY(orderBy.ASC())
|
2024-08-07 23:59:29 +07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-08-15 10:23:56 +07:00
|
|
|
func (api *API) DevicesList(ctx context.Context, req ListDevicesRequest) (resp []model.Devices, err error) {
|
2024-08-15 09:36:06 +07:00
|
|
|
ctx, span := tracer.Start(ctx, "DevicesList")
|
|
|
|
defer span.End()
|
|
|
|
|
2024-08-15 10:23:56 +07:00
|
|
|
stmt := req.Statement()
|
|
|
|
if err := stmt.QueryContext(ctx, api.DB, &resp); err != nil {
|
2024-08-15 09:36:06 +07:00
|
|
|
return resp, errs.Wrapw(err, "failed to list devices",
|
|
|
|
"request", req,
|
|
|
|
"query", stmt.DebugSql(),
|
|
|
|
)
|
2024-08-07 23:59:29 +07:00
|
|
|
}
|
|
|
|
return resp, err
|
|
|
|
}
|