add post userbook

needed a refactor to check the id in db during dto validation
This commit is contained in:
2025-10-17 01:13:35 +02:00
parent 7dcca84b7d
commit 9404013592
11 changed files with 157 additions and 30 deletions

View File

@@ -9,23 +9,55 @@ import (
"git.artlef.fr/PersonalLibraryManager/internal/i18nresource"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"gorm.io/gorm"
)
type HttpError struct {
StatusCode int
Err error
}
func ValidateId(db *gorm.DB, id uint, value any) error {
record := map[string]any{}
result := db.Model(value).First(&record, id)
if result.Error == nil {
return nil
}
if errors.Is(result.Error, gorm.ErrRecordNotFound) {
return HttpError{
StatusCode: http.StatusBadRequest,
Err: fmt.Errorf("Id %d could not be found for model %s", id, value),
}
} else {
return HttpError{
StatusCode: http.StatusInternalServerError,
Err: result.Error,
}
}
}
func ReturnErrorsAsJsonResponse(ac *appcontext.AppContext, err error) {
var httpError HttpError
var ve validator.ValidationErrors
if errors.As(err, &ve) {
ac.C.JSON(http.StatusBadRequest, gin.H{"error": getValidationErrors(ac, &ve)})
} else if errors.As(err, &httpError) {
ac.C.JSON(httpError.StatusCode, gin.H{"error": httpError.Err})
} else {
ac.C.JSON(http.StatusInternalServerError, gin.H{"error": err})
}
}
func (h HttpError) Error() string {
return fmt.Sprintf("%d: err %v", h.StatusCode, h.Err)
}
type apiValidationError struct {
Field string `json:"field"`
Err string `json:"error"`
}
func ManageBindingError(ac appcontext.AppContext, err error) {
var ve validator.ValidationErrors
if errors.As(err, &ve) {
ac.C.JSON(http.StatusBadRequest, getValidationErrors(ac, &ve))
} else {
ac.C.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
func getValidationErrors(ac appcontext.AppContext, ve *validator.ValidationErrors) []apiValidationError {
func getValidationErrors(ac *appcontext.AppContext, ve *validator.ValidationErrors) []apiValidationError {
errors := make([]apiValidationError, len(*ve))
for i, fe := range *ve {
errors[i] = apiValidationError{
@@ -36,7 +68,7 @@ func getValidationErrors(ac appcontext.AppContext, ve *validator.ValidationError
return errors
}
func computeValidationMessage(ac appcontext.AppContext, fe *validator.FieldError) string {
func computeValidationMessage(ac *appcontext.AppContext, fe *validator.FieldError) string {
tag := (*fe).Tag()
switch tag {
case "required":