2023-03-07 06:18:58 +00:00
|
|
|
package adapters
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2023-03-07 06:18:58 +00:00
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"github.com/gorilla/schema"
|
|
|
|
"github.com/hay-kot/homebox/backend/internal/sys/validate"
|
2023-04-09 18:39:43 +00:00
|
|
|
"github.com/hay-kot/httpkit/server"
|
2023-03-07 06:18:58 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var queryDecoder = schema.NewDecoder()
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
func DecodeQuery[T any](r *http.Request) (T, error) {
|
2023-03-07 06:18:58 +00:00
|
|
|
var v T
|
|
|
|
err := queryDecoder.Decode(&v, r.URL.Query())
|
|
|
|
if err != nil {
|
2023-03-21 04:32:10 +00:00
|
|
|
return v, errors.Wrap(err, "decoding error")
|
2023-03-07 06:18:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
err = validate.Check(v)
|
|
|
|
if err != nil {
|
2023-03-21 04:32:10 +00:00
|
|
|
return v, errors.Wrap(err, "validation error")
|
2023-03-07 06:18:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return v, nil
|
|
|
|
}
|
|
|
|
|
2023-03-21 05:48:22 +00:00
|
|
|
type Validator interface {
|
|
|
|
Validate() error
|
|
|
|
}
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
func DecodeBody[T any](r *http.Request) (T, error) {
|
2023-03-21 05:48:22 +00:00
|
|
|
var val T
|
2023-03-07 06:18:58 +00:00
|
|
|
|
2023-03-21 05:48:22 +00:00
|
|
|
err := server.Decode(r, &val)
|
2023-03-07 06:18:58 +00:00
|
|
|
if err != nil {
|
2023-03-21 05:48:22 +00:00
|
|
|
return val, errors.Wrap(err, "body decoding error")
|
2023-03-07 06:18:58 +00:00
|
|
|
}
|
|
|
|
|
2023-03-21 05:48:22 +00:00
|
|
|
err = validate.Check(val)
|
2023-03-07 06:18:58 +00:00
|
|
|
if err != nil {
|
2023-03-21 05:48:22 +00:00
|
|
|
return val, err
|
2023-03-07 06:18:58 +00:00
|
|
|
}
|
|
|
|
|
2023-03-21 05:48:22 +00:00
|
|
|
if v, ok := any(val).(Validator); ok {
|
|
|
|
err = v.Validate()
|
|
|
|
if err != nil {
|
|
|
|
return val, errors.Wrap(err, "validation error")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return val, nil
|
2023-03-07 06:18:58 +00:00
|
|
|
}
|
|
|
|
|
2023-03-21 04:32:10 +00:00
|
|
|
func RouteUUID(r *http.Request, key string) (uuid.UUID, error) {
|
2023-03-07 06:18:58 +00:00
|
|
|
ID, err := uuid.Parse(chi.URLParam(r, key))
|
|
|
|
if err != nil {
|
|
|
|
return uuid.Nil, validate.NewRouteKeyError(key)
|
|
|
|
}
|
|
|
|
return ID, nil
|
|
|
|
}
|