-
Notifications
You must be signed in to change notification settings - Fork 135
/
schema.go
61 lines (51 loc) · 1.35 KB
/
schema.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
package apierror
import (
"encoding/json"
"fmt"
"github.com/xeipuuv/gojsonschema"
)
type ValidationErrors struct {
Errors []*ValidationError
}
func (e ValidationErrors) Error() string {
return "schema validation failed"
}
func (e ValidationErrors) MarshalJSON() ([]byte, error) {
if len(e.Errors) > 1 {
errMap := map[string]interface{}{
"Reason": "multiple validation errors occurred",
"Errors": e.Errors,
}
return json.Marshal(errMap)
}
if len(e.Errors) == 1 {
return json.Marshal(e.Errors[0])
}
return nil, nil
}
type ValidationError struct {
Field string `json:"field"`
Type string `json:"type"`
Value interface{} `json:"value"`
Message string `json:"message"`
Details map[string]interface{} `json:"details"`
}
func (e ValidationError) Error() string {
return fmt.Sprintf("%s is invalid: %s", e.Field, e.Message)
}
func NewValidationError(err gojsonschema.ResultError) *ValidationError {
return &ValidationError{
Field: err.Field(),
Type: err.Type(),
Value: err.Value(),
Message: err.String(),
Details: err.Details(),
}
}
func NewValidationErrors(result *gojsonschema.Result) *ValidationErrors {
var errs []*ValidationError
for _, re := range result.Errors() {
errs = append(errs, NewValidationError(re))
}
return &ValidationErrors{Errors: errs}
}