-
Notifications
You must be signed in to change notification settings - Fork 14
/
validator.go
81 lines (67 loc) · 1.76 KB
/
validator.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package hitrix
import (
"context"
"fmt"
"reflect"
"github.com/99designs/gqlgen/graphql"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
vEn "github.com/go-playground/validator/v10/translations/en"
"github.com/vektah/gqlparser/v2/gqlerror"
)
func ValidateDirective() func(ctx context.Context, obj interface{}, next graphql.Resolver, rules string) (interface{}, error) {
return func(ctx context.Context, obj interface{}, next graphql.Resolver, rules string) (interface{}, error) {
originalValue, err := next(ctx)
if err != nil {
return nil, err
}
switch v := originalValue.(type) {
case string:
if v == "" {
return v, nil
}
default:
if v == nil || reflect.ValueOf(v).IsNil() {
return v, nil
}
}
validate := validator.New()
english := en.New()
uni := ut.New(english, english)
trans, _ := uni.GetTranslator("en")
_ = vEn.RegisterDefaultTranslations(validate, trans)
err = validate.Var(originalValue, rules)
errs := translateError(err, trans)
if err != nil {
for _, e := range errs {
graphql.AddError(ctx, &gqlerror.Error{
Path: graphql.GetPath(ctx),
Message: "Field" + e.Error(),
})
}
return originalValue, nil
}
return originalValue, nil
}
}
func Validate(ctx context.Context, callback func() bool) bool {
if graphql.GetErrors(ctx) != nil {
return false
}
if callback != nil {
return callback()
}
return true
}
func translateError(err error, trans ut.Translator) (errs []error) {
if err == nil {
return nil
}
validatorErrs := err.(validator.ValidationErrors)
for _, e := range validatorErrs {
translatedErr := fmt.Errorf(e.Translate(trans))
errs = append(errs, translatedErr)
}
return errs
}