added validation when adding a book
This commit is contained in:
@@ -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"`
|
||||
}
|
||||
|
||||
@@ -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
35
internal/api/validator.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user