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,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()