-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodel.go
57 lines (54 loc) · 1.78 KB
/
model.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package validator
import (
"context"
"strings"
"unicode"
)
type ErrorMessage struct {
Field string `mapstructure:"field" json:"field,omitempty" gorm:"column:field" bson:"field,omitempty" dynamodbav:"field,omitempty" firestore:"field,omitempty"`
Code string `mapstructure:"code" json:"code,omitempty" gorm:"column:code" bson:"code,omitempty" dynamodbav:"code,omitempty" firestore:"code,omitempty"`
Param string `mapstructure:"param" json:"param,omitempty" gorm:"column:param" bson:"param,omitempty" dynamodbav:"param,omitempty" firestore:"param,omitempty"`
Message string `mapstructure:"message" json:"message,omitempty" gorm:"column:message" bson:"message,omitempty" dynamodbav:"message,omitempty" firestore:"message,omitempty"`
}
type Validator interface {
Validate(ctx context.Context, model interface{}) ([]ErrorMessage, error)
}
type MapValidator interface {
Validate(ctx context.Context, model map[string]interface{}) ([]ErrorMessage, error)
}
func RemoveRequiredError(errors []ErrorMessage) []ErrorMessage {
if errors == nil || len(errors) == 0 {
return errors
}
errs := make([]ErrorMessage, 0)
for _, s := range errors {
if s.Code != "required" && !strings.HasPrefix(s.Code, "minlength") {
errs = append(errs, s)
} else if strings.Index(s.Field, ".") >= 0 {
errs = append(errs, s)
}
}
return errs
}
func FormatErrorField(s string) string {
splitField := strings.Split(s, ".")
length := len(splitField)
if length == 1 {
return lcFirstChar(splitField[0])
} else if length > 1 {
var tmp []string
for _, v := range splitField[1:] {
tmp = append(tmp, lcFirstChar(v))
}
return strings.Join(tmp, ".")
}
return s
}
func lcFirstChar(s string) string {
if len(s) > 0 {
runes := []rune(s)
runes[0] = unicode.ToLower(runes[0])
return string(runes)
}
return s
}