Redmage/server/routes/device_list.go

51 lines
1.3 KiB
Go
Raw Normal View History

2024-04-14 17:30:04 +07:00
package routes
import (
"encoding/json"
"net/http"
"strconv"
2024-04-24 22:26:04 +07:00
"strings"
2024-04-14 17:30:04 +07:00
"github.com/tigorlazuardi/redmage/api"
2024-04-24 22:26:04 +07:00
"github.com/tigorlazuardi/redmage/pkg/errs"
2024-04-14 17:30:04 +07:00
"github.com/tigorlazuardi/redmage/pkg/log"
)
func (routes *Routes) APIDeviceList(rw http.ResponseWriter, r *http.Request) {
ctx, span := tracer.Start(r.Context(), "*Routes.APIDeviceList")
defer span.End()
query := parseApiDeviceListQueries(r)
result, err := routes.API.DevicesList(ctx, query)
if err != nil {
2024-04-24 22:26:04 +07:00
code, message := errs.HTTPMessage(err)
rw.WriteHeader(code)
_ = json.NewEncoder(rw).Encode(map[string]string{"error": message})
2024-04-14 17:30:04 +07:00
return
}
if err := json.NewEncoder(rw).Encode(result); err != nil {
log.New(ctx).Err(err).Error("failed to marshal json api devices")
}
}
func parseApiDeviceListQueries(req *http.Request) (params api.DevicesListParams) {
params.All, _ = strconv.ParseBool(req.FormValue("all"))
params.Offset, _ = strconv.ParseInt(req.FormValue("offset"), 10, 64)
params.Limit, _ = strconv.ParseInt(req.FormValue("limit"), 10, 64)
params.Q = req.FormValue("q")
params.OrderBy = req.FormValue("order")
2024-04-24 22:26:04 +07:00
params.Sort = strings.ToLower(req.FormValue("sort"))
2024-04-14 17:30:04 +07:00
if params.Limit < 1 {
params.Limit = 10
}
if params.OrderBy == "" {
params.OrderBy = "name"
}
2024-04-14 17:30:04 +07:00
return params
}