-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathschema.go
338 lines (296 loc) · 9.6 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package vjson
import (
"encoding/json"
"github.com/hashicorp/go-multierror"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/tidwall/gjson"
"io/ioutil"
"os"
)
// Schema is the type for declaring a JSON schema and validating a json object.
type Schema struct {
Fields []Field `json:"fields"`
}
// SchemaSpec is used for parsing a Schema
type SchemaSpec struct {
Fields []map[string]interface{} `json:"fields"`
}
// UnmarshalJSON is implemented for parsing a Schema. it overrides json.Unmarshal behaviour.
func (s *Schema) UnmarshalJSON(bytes []byte) error {
var schemaSpec SchemaSpec
err := json.Unmarshal(bytes, &schemaSpec)
if err != nil {
return errors.Wrap(err, "could not unmarshal to SchemaSpec")
}
s.Fields = make([]Field, 0, len(schemaSpec.Fields))
var result error
for _, fieldSpec := range schemaSpec.Fields {
field, err := s.getField(fieldSpec)
if err != nil {
result = multierror.Append(result, err)
continue
}
s.Fields = append(s.Fields, field)
}
return result
}
func (s *Schema) getField(fieldSpec map[string]interface{}) (Field, error) {
fieldTypeRaw, found := fieldSpec[typeKey]
if found {
fieldTypeStr, ok := fieldTypeRaw.(string)
if ok {
fieldType := fieldType(fieldTypeStr)
switch fieldType {
case integerType:
{
field, err := s.getIntegerField(fieldSpec)
if err != nil {
return nil, err
}
return field, nil
}
case floatType:
{
field, err := s.getFloatField(fieldSpec)
if err != nil {
return nil, err
}
return field, nil
}
case stringType:
{
field, err := s.getStringField(fieldSpec)
if err != nil {
return nil, err
}
return field, nil
}
case arrayType:
{
field, err := s.getArrayField(fieldSpec)
if err != nil {
return nil, err
}
return field, nil
}
case booleanType:
{
field, err := s.getBooleanField(fieldSpec)
if err != nil {
return nil, err
}
return field, nil
}
case objectType:
{
field, err := s.getObjectField(fieldSpec)
if err != nil {
return nil, err
}
return field, nil
}
case nullType:
{
field, err := s.getNullField(fieldSpec)
if err != nil {
return nil, err
}
return field, nil
}
default:
{
return nil, errors.Errorf("Invalid type: %s", fieldType)
}
}
}
return nil, errors.Errorf("invalid field type")
}
return nil, errors.Errorf("field type not found")
}
func (s *Schema) getIntegerField(fieldSpec map[string]interface{}) (*IntegerField, error) {
var intSpec IntegerFieldSpec
err := mapstructure.Decode(fieldSpec, &intSpec)
if err != nil {
return nil, errors.Wrap(err, "could not decode integer field to IntegerFieldSpec")
}
if intSpec.Name == "" {
return nil, errors.Errorf("name field is required for an integer field")
}
_, minValidation := fieldSpec["min"]
_, maxValidation := fieldSpec["max"]
_, signValidation := fieldSpec["positive"]
_, rangeValidation := fieldSpec["ranges"]
intField := NewInteger(intSpec, minValidation, maxValidation, signValidation, rangeValidation)
return intField, nil
}
func (s *Schema) getFloatField(fieldSpec map[string]interface{}) (*FloatField, error) {
var floatSpec FloatFieldSpec
err := mapstructure.Decode(fieldSpec, &floatSpec)
if err != nil {
return nil, errors.Wrap(err, "could not decode float field to IntegerFieldSpec")
}
if floatSpec.Name == "" {
return nil, errors.Errorf("name field is required for a float field")
}
_, minValidation := fieldSpec["min"]
_, maxValidation := fieldSpec["max"]
_, signValidation := fieldSpec["positive"]
_, rangeValidation := fieldSpec["ranges"]
floatField := NewFloat(floatSpec, minValidation, maxValidation, signValidation, rangeValidation)
return floatField, nil
}
func (s *Schema) getStringField(fieldSpec map[string]interface{}) (*StringField, error) {
var stringSpec StringFieldSpec
err := mapstructure.Decode(fieldSpec, &stringSpec)
if err != nil {
return nil, errors.Wrap(err, "could not decode float field to IntegerFieldSpec")
}
if stringSpec.Name == "" {
return nil, errors.Errorf("name field is required for a string field")
}
_, minLenValidation := fieldSpec["min_length"]
_, maxLenValidation := fieldSpec["max_length"]
_, formatValidation := fieldSpec["format"]
_, choiceValidation := fieldSpec["choices"]
stringField := NewString(stringSpec, minLenValidation, maxLenValidation, formatValidation, choiceValidation)
return stringField, nil
}
func (s *Schema) getArrayField(fieldSpec map[string]interface{}) (*ArrayField, error) {
var arraySpec ArrayFieldSpec
err := mapstructure.Decode(fieldSpec, &arraySpec)
if err != nil {
return nil, errors.Wrap(err, "could not decode array field to ArrayFieldSpec")
}
if arraySpec.Name == "" {
return nil, errors.Errorf("name field is required for an array field")
}
itemsFieldSpecRaw, found := fieldSpec["items"]
if !found {
return nil, errors.Errorf("items key is missing for array field name: %s", arraySpec.Name)
}
itemsFieldSpec, ok := itemsFieldSpecRaw.(map[string]interface{})
if !ok {
return nil, errors.Errorf("invalid format for items key for array field name: %s", arraySpec.Name)
}
itemField, err := s.getField(itemsFieldSpec)
if err != nil {
return nil, errors.Wrapf(err, "could not get item field of array field name: %s", arraySpec.Name)
}
_, minLenValidation := fieldSpec["min_length"]
_, maxLenValidation := fieldSpec["max_length"]
arrayField := NewArray(arraySpec, itemField, minLenValidation, maxLenValidation)
return arrayField, nil
}
func (s *Schema) getBooleanField(fieldSpec map[string]interface{}) (*BooleanField, error) {
var booleanSpec BooleanFieldSpec
err := mapstructure.Decode(fieldSpec, &booleanSpec)
if err != nil {
return nil, errors.Wrap(err, "could not decode boolean field to BooleanFieldSpec")
}
if booleanSpec.Name == "" {
return nil, errors.Errorf("name field is required for a boolean field")
}
_, valueValidation := fieldSpec["value"]
booleanField := NewBoolean(booleanSpec, valueValidation)
return booleanField, nil
}
func (s *Schema) getObjectField(fieldSpec map[string]interface{}) (*ObjectField, error) {
var objectSpec ObjectFieldSpec
err := mapstructure.Decode(fieldSpec, &objectSpec)
if err != nil {
return nil, errors.Wrap(err, "could not decode object field to ObjectFieldSpec")
}
if objectSpec.Name == "" {
return nil, errors.Errorf("name field is required for an object field")
}
schemaSpecRaw, found := fieldSpec["schema"]
if !found {
return nil, errors.Errorf("schema key is missing for object field name: %s", objectSpec.Name)
}
schemaSpec, ok := schemaSpecRaw.(map[string]interface{})
if !ok {
return nil, errors.Errorf("invalid format for schema key for object field name: %s", objectSpec.Name)
}
jsonSchemaSpec, err := json.Marshal(schemaSpec)
if err != nil {
return nil, errors.Errorf("could not marshal schema to json for object field name: %s", objectSpec.Name)
}
var schema Schema
err = json.Unmarshal(jsonSchemaSpec, &schema)
if err != nil {
return nil, errors.Errorf("could not unmarshal schema spec to schema for object field name: %s", objectSpec.Name)
}
objectField := NewObject(objectSpec, schema)
return objectField, nil
}
func (s *Schema) getNullField(fieldSpec map[string]interface{}) (*NullField, error) {
var nullSpec NullFieldSpec
err := mapstructure.Decode(fieldSpec, &nullSpec)
if err != nil {
return nil, errors.Wrap(err, "could not decode null field to NullFieldSpec")
}
if nullSpec.Name == "" {
return nil, errors.Errorf("name field is required for a null field")
}
nullField := NewNull(nullSpec)
return nullField, nil
}
// ValidateBytes receives a byte array of a json object and validates it according to the specified Schema.
// it returns an error if the input is invalid.
func (s *Schema) ValidateBytes(input []byte) error {
if gjson.ValidBytes(input) {
jsonObject := gjson.ParseBytes(input)
return s.validateJSON(jsonObject)
}
return errors.Errorf("could not parse json input.")
}
// ValidateString is like ValidateBytes but it receives the json object as string input.
func (s *Schema) ValidateString(input string) error {
if gjson.Valid(input) {
jsonObject := gjson.Parse(input)
return s.validateJSON(jsonObject)
}
return errors.Errorf("could not parse json input.")
}
func (s *Schema) validateJSON(json gjson.Result) error {
var result error
for _, field := range s.Fields {
fieldName := field.GetName()
fieldValue := json.Get(fieldName).Value()
err := field.Validate(fieldValue)
if err != nil {
result = multierror.Append(result, errors.Wrapf(err, "Field %s is invalid.", fieldName))
}
}
return result
}
// NewSchema is the constructor for Schema. it receives a list of Field in its arguments.
func NewSchema(fields ...Field) Schema {
return Schema{Fields: fields}
}
// ReadFromString is for parsing a Schema from a string input.
func ReadFromString(input string) (*Schema, error) {
return ReadFromBytes([]byte(input))
}
// ReadFromBytes is for parsing a Schema from a byte array input.
func ReadFromBytes(input []byte) (*Schema, error) {
var s Schema
err := json.Unmarshal(input, &s)
if err != nil {
return nil, errors.Wrapf(err, "could not unmarshal file given to Schema")
}
return &s, nil
}
// ReadFromFile is for parsing a Schema from a file input.
func ReadFromFile(filePath string) (*Schema, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, errors.Wrapf(err, "could not open file given, path: %s", filePath)
}
input, err := ioutil.ReadAll(file)
if err != nil {
return nil, errors.Wrapf(err, "could not read file given, path: %s", filePath)
}
return ReadFromBytes(input)
}