added validation when adding a book

This commit is contained in:
2025-09-24 17:06:39 +02:00
parent 8432902df1
commit 2f0a9b5127
7 changed files with 105 additions and 13 deletions

View File

@@ -1,7 +1,7 @@
package api
type bookPostCreate struct {
Title string `json:"title" binding:"required"`
Author string `json:"author"`
Title string `json:"title" binding:"required,max=300"`
Author string `json:"author" binding:"max=100"`
Rating int `json:"rating" binding:"min=0,max=10"`
}

View File

@@ -1,10 +1,12 @@
package api
import (
"errors"
"net/http"
"git.artlef.fr/PersonalLibraryManager/internal/model"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator/v10"
"gorm.io/gorm"
)
@@ -18,7 +20,12 @@ func PostBookHandler(c *gin.Context, db *gorm.DB) {
var book bookPostCreate
err := c.ShouldBindJSON(&book)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
var ve validator.ValidationErrors
if errors.As(err, &ve) {
c.JSON(http.StatusBadRequest, getValidationErrors(&ve))
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
return
}
bookDb := book.toBook()

35
internal/api/validator.go Normal file
View File

@@ -0,0 +1,35 @@
package api
import (
"fmt"
"github.com/go-playground/validator/v10"
)
type apiValidationError struct {
Field string `json:"field"`
Err string `json:"error"`
}
func getValidationErrors(ve *validator.ValidationErrors) []apiValidationError {
errors := make([]apiValidationError, len(*ve))
for i, fe := range *ve {
errors[i] = apiValidationError{
Field: fe.Field(),
Err: computeValidationMessage(&fe),
}
}
return errors
}
func computeValidationMessage(fe *validator.FieldError) string {
tag := (*fe).Tag()
switch tag {
case "required":
return fmt.Sprintf("%s is required.", (*fe).Field())
case "max":
return fmt.Sprintf("%s is too long. It should be under %s characters.", (*fe).Field(), (*fe).Param())
default:
return fmt.Sprintf("Validation failed for '%s' property.", tag)
}
}