chore: init repository
This commit is contained in:
43
internal/storage/validators/error.go
Executable file
43
internal/storage/validators/error.go
Executable file
@@ -0,0 +1,43 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gopkg.in/go-playground/validator.v9"
|
||||
"john/internal/storage/model"
|
||||
"john/internal/utils"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var regexpValidatorNamespacePrefix = regexp.MustCompile(`^\w+\.`)
|
||||
|
||||
func NewDataValidationAPIError(err error) model.APIError {
|
||||
apiErr := model.ErrDataValidation
|
||||
if err != nil {
|
||||
if _, ok := err.(*validator.InvalidValidationError); ok {
|
||||
utils.GetLogger().WithError(err).WithField("templateAPIErr", apiErr).Error("InvalidValidationError")
|
||||
} else {
|
||||
for _, e := range err.(validator.ValidationErrors) {
|
||||
reason := e.Tag()
|
||||
if _, ok := CustomValidators[e.Tag()]; ok {
|
||||
reason = truncatingSprintf(CustomValidators[e.Tag()].Message, e.Param())
|
||||
}
|
||||
|
||||
namespaceWithoutStructName := regexpValidatorNamespacePrefix.ReplaceAllString(e.Namespace(), "")
|
||||
fe := model.FieldError{
|
||||
Field: namespaceWithoutStructName,
|
||||
Constraint: e.Tag(),
|
||||
Description: reason,
|
||||
}
|
||||
apiErr.Details = append(apiErr.Details, fe)
|
||||
}
|
||||
}
|
||||
}
|
||||
return apiErr
|
||||
}
|
||||
|
||||
// truncatingSprintf is used as fmt.Sprintf but allow to truncate the additional parameters given when there is more parameters than %v in str
|
||||
func truncatingSprintf(str string, args ...interface{}) string {
|
||||
n := strings.Count(str, "%v")
|
||||
return fmt.Sprintf(str, args[:n]...)
|
||||
}
|
||||
34
internal/storage/validators/validators.go
Executable file
34
internal/storage/validators/validators.go
Executable file
@@ -0,0 +1,34 @@
|
||||
package validators
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"gopkg.in/go-playground/validator.v9"
|
||||
)
|
||||
|
||||
var (
|
||||
CustomValidators = map[string]customValidator{
|
||||
"enum": {
|
||||
Message: "This field should be in: %v",
|
||||
Validator: validateEnum,
|
||||
},
|
||||
"required": {
|
||||
Message: "This field is required and cannot be empty",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
type customValidator struct {
|
||||
Message string
|
||||
Validator validator.FuncCtx
|
||||
}
|
||||
|
||||
func validateEnum(ctx context.Context, fl validator.FieldLevel) bool {
|
||||
for _, v := range strings.Split(fl.Param(), " ") {
|
||||
if v == fl.Field().String() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user