2024-05-07 16:48:15 +07:00
|
|
|
package routes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2024-05-07 20:51:00 +07:00
|
|
|
"github.com/gosimple/slug"
|
2024-05-07 16:48:15 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/pkg/errs"
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/log"
|
2024-05-08 14:09:00 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/views/devices/put"
|
2024-05-07 16:48:15 +07:00
|
|
|
)
|
|
|
|
|
|
|
|
func (routes *Routes) DevicesValidateSlugHTMX(rw http.ResponseWriter, req *http.Request) {
|
|
|
|
ctx, span := tracer.Start(req.Context(), "*Routes.ValidateSlugHTMX")
|
|
|
|
defer span.End()
|
|
|
|
|
2024-05-08 10:10:23 +07:00
|
|
|
var data put.SlugInputData
|
2024-05-07 20:51:00 +07:00
|
|
|
data.Value = slug.Make(req.FormValue("slug"))
|
2024-05-07 16:48:15 +07:00
|
|
|
if data.Value == "" {
|
2024-05-08 10:10:23 +07:00
|
|
|
if err := put.SlugInput(data).Render(ctx, rw); err != nil {
|
2024-05-07 16:48:15 +07:00
|
|
|
log.New(ctx).Err(err).Error("failed to render slug input")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
exist, err := routes.API.DevicesValidateSlug(ctx, data.Value)
|
|
|
|
if err != nil {
|
|
|
|
log.New(ctx).Err(err).Error("failed to validate slug")
|
|
|
|
code, message := errs.HTTPMessage(err)
|
|
|
|
rw.WriteHeader(code)
|
|
|
|
data.Error = message
|
2024-05-08 10:10:23 +07:00
|
|
|
if err := put.SlugInput(data).Render(ctx, rw); err != nil {
|
2024-05-07 16:48:15 +07:00
|
|
|
log.New(ctx).Err(err).Error("failed to render slug input")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if exist {
|
|
|
|
data.Error = "Device with this identifier already exist"
|
|
|
|
rw.WriteHeader(http.StatusConflict)
|
2024-05-08 10:10:23 +07:00
|
|
|
if err := put.SlugInput(data).Render(ctx, rw); err != nil {
|
2024-05-07 16:48:15 +07:00
|
|
|
log.New(ctx).Err(err).Error("failed to render slug input")
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
data.Valid = "Identifier is available"
|
|
|
|
|
2024-05-08 10:10:23 +07:00
|
|
|
if err := put.SlugInput(data).Render(ctx, rw); err != nil {
|
2024-05-07 16:48:15 +07:00
|
|
|
log.New(ctx).Err(err).Error("failed to render slug input")
|
|
|
|
}
|
|
|
|
}
|