-
Notifications
You must be signed in to change notification settings - Fork 13
/
validator.go
53 lines (43 loc) · 1.07 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
package hitrix
import (
"context"
"reflect"
"github.com/coretrix/hitrix/pkg/helper"
"github.com/99designs/gqlgen/graphql"
"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
}
}
errs := helper.NewValidator().Validate(originalValue, rules)
for _, e := range errs {
graphql.AddError(ctx, &gqlerror.Error{
Path: graphql.GetPath(ctx),
Message: "Field" + e.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
}