Refactor api code: split between packages
This commit is contained in:
51
internal/myvalidator/myvalidator.go
Normal file
51
internal/myvalidator/myvalidator.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package myvalidator
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/appcontext"
|
||||
"git.artlef.fr/PersonalLibraryManager/internal/i18nresource"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/go-playground/validator/v10"
|
||||
)
|
||||
|
||||
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 {
|
||||
errors := make([]apiValidationError, len(*ve))
|
||||
for i, fe := range *ve {
|
||||
errors[i] = apiValidationError{
|
||||
Field: fe.Field(),
|
||||
Err: computeValidationMessage(ac, &fe),
|
||||
}
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
func computeValidationMessage(ac appcontext.AppContext, fe *validator.FieldError) string {
|
||||
tag := (*fe).Tag()
|
||||
switch tag {
|
||||
case "required":
|
||||
return i18nresource.GetTranslatedMessage(ac, "ValidationRequired")
|
||||
case "min":
|
||||
return fmt.Sprintf(i18nresource.GetTranslatedMessage(ac, "ValidationTooShort"), (*fe).Param())
|
||||
case "max":
|
||||
return fmt.Sprintf(i18nresource.GetTranslatedMessage(ac, "ValidationTooLong"), (*fe).Param())
|
||||
default:
|
||||
return fmt.Sprintf(i18nresource.GetTranslatedMessage(ac, "ValidationPropertyFail"), tag)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user