-
Notifications
You must be signed in to change notification settings - Fork 13
/
validator.go
62 lines (51 loc) · 1.25 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
package hitrix
import (
"context"
"reflect"
"github.com/99designs/gqlgen/graphql"
"github.com/vektah/gqlparser/v2/gqlerror"
"github.com/coretrix/hitrix/pkg/helper"
)
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
}
}
errs := helper.NewValidator().Validate(originalValue, rules)
if len(errs) > 0 {
if len(errs) > 1 {
for i := 1; i < len(errs); i++ {
graphql.AddError(ctx, &gqlerror.Error{
Path: graphql.GetPath(ctx),
Message: "Field" + errs[i].Error(),
})
}
}
return nil, &gqlerror.Error{
Path: graphql.GetPath(ctx),
Message: "Field" + errs[0].Error(),
}
}
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
}