-
Notifications
You must be signed in to change notification settings - Fork 4
/
object.go
781 lines (715 loc) · 20.8 KB
/
object.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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
package schema
import (
"encoding/json"
"fmt"
"reflect"
"strings"
)
// Object holds the definition for objects comprised of defined fields.
type Object interface {
Type
ID() string
Properties() map[string]*PropertySchema
// GetDefaults returns the defaults in a serialized form.
GetDefaults() map[string]any
}
// NewObjectSchema creates a new object definition.
// If you need it tied to a struct, use NewStructMappedObjectSchema instead.
func NewObjectSchema(id string, properties map[string]*PropertySchema) *ObjectSchema {
var anyValue any
return &ObjectSchema{
id,
properties,
extractObjectDefaultValues(properties),
nil,
reflect.TypeOf(anyValue),
nil,
}
}
// ObjectSchema is the implementation of the object schema type.
type ObjectSchema struct {
IDValue string `json:"id"`
PropertiesValue map[string]*PropertySchema `json:"properties"`
defaultValues map[string]any // Key: Object field name, value: The default value
defaultValue any
defaultValueType reflect.Type
fieldCache map[string]reflect.StructField
}
func (o *ObjectSchema) ReflectedType() reflect.Type {
if o.fieldCache != nil {
return o.defaultValueType
}
return reflect.TypeOf(map[string]any{})
}
func (o *ObjectSchema) GetDefaults() map[string]any {
if o.defaultValues == nil {
o.defaultValues = extractObjectDefaultValues(o.PropertiesValue)
}
return o.defaultValues
}
func (o *ObjectSchema) ApplyNamespace(objects map[string]*ObjectSchema, namespace string) {
for _, property := range o.PropertiesValue {
property.ApplyNamespace(objects, namespace)
}
}
func (o *ObjectSchema) ValidateReferences() error {
for _, property := range o.PropertiesValue {
err := property.ValidateReferences()
if err != nil {
return err
}
}
return nil
}
func (o *ObjectSchema) TypeID() TypeID {
return TypeIDObject
}
func (o *ObjectSchema) ID() string {
return o.IDValue
}
func (o *ObjectSchema) Properties() map[string]*PropertySchema {
return o.PropertiesValue
}
func (o *ObjectSchema) Unserialize(data any) (result any, err error) {
v := reflect.ValueOf(data)
if v.Kind() != reflect.Map {
return nil, &ConstraintError{
Message: fmt.Sprintf("Must be a map, %T given", data),
}
}
rawData, err := o.convertData(v)
if err != nil {
return nil, err
}
if err := o.validateFieldInterdependencies(rawData); err != nil {
return nil, err
}
if o.fieldCache != nil {
return o.unserializeToStruct(rawData)
}
return rawData, nil
}
func (o *ObjectSchema) unserializeToStruct(rawData map[string]any) (any, error) {
reflectType := reflect.TypeOf(o.defaultValue)
var reflectedValue reflect.Value
if reflectType.Kind() != reflect.Pointer {
reflectedValue = reflect.New(reflectType)
} else {
reflectedValue = reflect.New(reflectType.Elem())
}
for key, value := range rawData {
val := value
elem := reflectedValue.Elem()
field := elem.FieldByIndex(o.fieldCache[key].Index)
f := field
v := reflect.ValueOf(val)
var recoveredError error
func() {
defer func() {
e := recover()
if e != nil {
var ok bool
recoveredError, ok = e.(error)
if !ok {
recoveredError = fmt.Errorf("%v", e)
}
}
}()
if field.Kind() == reflect.Pointer && v.Kind() != reflect.Pointer {
f = reflect.New(f.Type().Elem())
f.Elem().Set(v.Convert(f.Elem().Type()))
field.Set(f)
} else {
f.Set(v.Convert(f.Type()))
}
}()
if recoveredError != nil {
return nil, &ConstraintError{
"Field cannot be set",
[]string{key},
recoveredError,
}
}
}
reflectType = reflect.TypeOf(o.defaultValue)
var result any
if reflectType.Kind() != reflect.Pointer {
result = reflectedValue.Elem().Interface()
} else {
result = reflectedValue.Interface()
}
return result, nil
}
func (o *ObjectSchema) serializeMap(data map[string]any) (any, error) {
if err := o.validateFieldInterdependencies(data); err != nil {
return nil, err
}
rawSerializedData := map[string]any{}
for k, v := range data {
property, ok := o.PropertiesValue[k]
if !ok {
return nil, o.invalidKeyError(k)
}
serializedValue, err := property.Serialize(v)
if err != nil {
return nil, ConstraintErrorAddPathSegment(err, k)
}
rawSerializedData[k] = serializedValue
}
return rawSerializedData, nil
}
func (o *ObjectSchema) serializeStruct(data any) (any, error) {
if reflect.TypeOf(data) != o.ReflectedType() {
return o.defaultValue, &ConstraintError{
Message: fmt.Sprintf("%T is not a valid data type, expected %s.", data, o.ReflectedType().String()),
}
}
rawData := map[string]any{}
v := reflect.ValueOf(data)
if v.Kind() == reflect.Pointer && v.IsNil() {
return nil, &ConstraintError{
Message: fmt.Sprintf("Nil value passed instead of %T", o.defaultValue),
}
}
for propertyID, property := range o.PropertiesValue {
a, err := o.extractPropertyValue(propertyID, v, property)
if err != nil {
return nil, err
}
if a != nil {
rawData[propertyID] = *a
}
}
if err := o.validateFieldInterdependencies(rawData); err != nil {
return nil, err
}
return rawData, nil
}
func (o *ObjectSchema) extractPropertyValue(propertyID string, v reflect.Value, property *PropertySchema) (*any, error) {
valPtr := o.getFieldReflection(propertyID, v, property)
if valPtr == nil {
return nil, nil
}
value := valPtr.Interface()
if property.emptyIsDefault {
// Handle the case where the empty value corresponds to the default value.
defaultValue := reflect.New(property.ReflectedType()).Elem().Convert(valPtr.Type()).Interface()
if defaultValue == value {
return nil, nil
}
}
serializedData, err := property.Serialize(value)
if err != nil {
return nil, ConstraintErrorAddPathSegment(err, propertyID)
}
return &serializedData, nil
}
func (o *ObjectSchema) getFieldReflection(propertyID string, v reflect.Value, property *PropertySchema) *reflect.Value {
field := o.fieldCache[propertyID]
var val reflect.Value
if v.Kind() == reflect.Pointer {
val = v.Elem().FieldByName(field.Name)
} else {
val = v.FieldByName(field.Name)
}
if val.Kind() == reflect.Pointer {
if val.IsNil() {
return nil
}
if property.ReflectedType().Kind() != reflect.Pointer {
val = val.Elem()
}
}
if val.Interface() == nil {
return nil
}
return &val
}
func (o *ObjectSchema) Serialize(data any) (any, error) {
if o.fieldCache != nil {
return o.serializeStruct(data)
}
d, ok := data.(map[string]any)
if !ok {
return nil, &ConstraintError{
Message: fmt.Sprintf("%T is not a valid data type for an object schema.", d),
}
}
return o.serializeMap(d)
}
func (o *ObjectSchema) validateMap(data map[string]any) error {
if err := o.validateFieldInterdependencies(data); err != nil {
return err
}
for k, v := range data {
property, ok := o.PropertiesValue[k]
if !ok {
return o.invalidKeyError(k)
}
if err := property.Validate(v); err != nil {
return ConstraintErrorAddPathSegment(err, k)
}
}
return nil
}
func (o *ObjectSchema) validateMapTypesCompatibility(data map[string]any) error {
// Note: Interdependencies are not validated here yet.
// Verify that all present fields match the self schema
for k, v := range data {
property, ok := o.PropertiesValue[k]
if !ok {
return o.invalidKeyError(k)
}
if err := property.ValidateCompatibility(v); err != nil {
return ConstraintErrorAddPathSegment(err, k)
}
}
// Verify that all required fields are present
for k, property := range o.PropertiesValue {
if property.Required() && data[k] == nil {
return &ConstraintError{
Message: fmt.Sprintf("error while validating fields of objects %s, could not find required field %s", o.ReflectedType().String(), k),
}
}
}
return nil
}
func (o *ObjectSchema) validateStruct(data any) error {
if reflect.TypeOf(data) != o.ReflectedType() {
return &ConstraintError{
Message: fmt.Sprintf("%T is not a valid data type, expected %s.", data, o.ReflectedType().String()),
}
}
rawData := map[string]any{}
v := reflect.ValueOf(data)
if v.Kind() == reflect.Pointer && v.IsNil() {
return &ConstraintError{
Message: fmt.Sprintf("Nil value passed instead of %T", o.defaultValue),
}
}
for propertyID, property := range o.PropertiesValue {
valPtr := o.getFieldReflection(propertyID, v, property)
if valPtr == nil {
continue
}
value := valPtr.Interface()
if property.emptyIsDefault {
// Handle the case where the empty value corresponds to the default value.
defaultValue := reflect.New(property.ReflectedType()).Elem().Convert(valPtr.Type()).Interface()
if reflect.DeepEqual(defaultValue, value) {
continue
}
}
if err := property.Validate(value); err != nil {
return ConstraintErrorAddPathSegment(err, propertyID)
}
rawData[propertyID] = value
}
return o.validateFieldInterdependencies(rawData)
}
func (o *ObjectSchema) validateSchemaCompatibility(schemaType Object) error {
fieldData := map[string]any{}
// Validate IDs. This is important because the IDs should match.
if schemaType.ID() != o.ID() {
return &ConstraintError{
Message: fmt.Sprintf("validation failed for object schema ID %s. ID %s does not match.",
o.ID(), schemaType.ID()),
}
}
// Copy all properties to the variable for validating later.
for key, value := range schemaType.Properties() {
fieldData[key] = value
}
// Now validate object fields
return o.validateMapTypesCompatibility(fieldData)
}
func (o *ObjectSchema) validateRawCompatibility(typeOrData any) error {
// Check if it's just a string->interface map. If so, pass it into validateMapTypes
// Can't validate IDs, but that's acceptable. The only thing that matters in those cases is that the properties match.
// The reason for that is because we're checking if fields conform to the requirements of the object in this else section.
if fieldData, ok := typeOrData.(map[string]any); ok {
// Validate object fields
return o.validateMapTypesCompatibility(fieldData)
}
// Try validating as data
_, err := o.Unserialize(typeOrData)
if err != nil {
return &ConstraintError{
Message: fmt.Sprintf("%T is not a valid data type or schema for an object schema (%s)", typeOrData, err),
}
} else {
return nil
}
}
func (o *ObjectSchema) ValidateCompatibility(typeOrData any) error {
// Check if it's a schema. If it is, verify it. If not, verify it as data.
schemaType, ok := ConvertToObjectSchema(typeOrData)
if ok {
// It's a schema, so see if the schema matches
return o.validateSchemaCompatibility(schemaType)
} else {
// It's not a schema, so it's ether a map of fields or raw data
return o.validateRawCompatibility(typeOrData)
}
}
func (o *ObjectSchema) Validate(data any) error {
if o.fieldCache != nil {
return o.validateStruct(data)
}
d, ok := data.(map[string]any)
if !ok {
return &ConstraintError{
Message: fmt.Sprintf("%T is not a valid data type for an object schema", d),
}
}
return o.validateMap(d)
}
func (o *ObjectSchema) applySubObjectDefaultValues(propertyID string, property *PropertySchema, rawData map[string]any) {
reflectedType := property.ReflectedType()
if reflectedType.Kind() == reflect.Pointer {
return
}
var subObject Object
switch property.TypeID() {
case TypeIDRef:
subObject = property.Type().(Ref).GetObject()
case TypeIDObject:
subObject = property.Type().(Object)
default:
return
}
data := map[string]any{}
if _, ok := rawData[propertyID]; ok {
data = rawData[propertyID].(map[string]any)
}
subObjectDefaults := subObject.GetDefaults()
for k, v := range subObjectDefaults {
data[k] = v
}
for subPropertyID, subProperty := range subObject.Properties() {
o.applySubObjectDefaultValues(subPropertyID, subProperty, data)
}
if len(data) != 0 {
rawData[propertyID] = data
}
}
func (o *ObjectSchema) convertData(v reflect.Value) (map[string]any, error) {
rawData := make(map[string]any, v.Len())
for _, key := range v.MapKeys() {
stringKey, ok := key.Interface().(string)
if !ok {
return nil, o.invalidKeyError(key.Interface())
}
if _, ok := o.PropertiesValue[stringKey]; !ok {
return nil, o.invalidKeyError(stringKey)
}
rawData[stringKey] = v.MapIndex(key).Interface()
}
for propertyID := range o.PropertiesValue {
_, isSet := rawData[propertyID]
if !isSet {
if defaultValue, ok := o.GetDefaults()[propertyID]; ok {
rawData[propertyID] = defaultValue
}
if o.fieldCache != nil {
o.applySubObjectDefaultValues(propertyID, o.PropertiesValue[propertyID], rawData)
}
}
}
for propertyID, property := range o.PropertiesValue {
if d, ok := rawData[propertyID]; ok {
unserializedData, err := property.Unserialize(d)
if err != nil {
return nil, ConstraintErrorAddPathSegment(err, propertyID)
}
rawData[propertyID] = unserializedData
}
}
return rawData, nil
}
func (o *ObjectSchema) validateFieldInterdependencies(rawData map[string]any) error {
for propertyID, property := range o.PropertiesValue {
if _, isSet := rawData[propertyID]; isSet {
if err := o.validatePropertyInterdependenciesIfSet(rawData, propertyID, property); err != nil {
return err
}
} else {
err := o.validatePropertyInterdependenciesIfUnset(rawData, propertyID, property)
if err != nil {
return err
}
}
}
return nil
}
func (o *ObjectSchema) validatePropertyInterdependenciesIfUnset(
rawData map[string]any,
propertyID string,
property *PropertySchema,
) error {
if property.Required() {
return &ConstraintError{
Message: "This field is required",
Path: []string{propertyID},
}
}
for _, requiredIf := range property.RequiredIf() {
if _, set := rawData[requiredIf]; set {
return &ConstraintError{
Message: fmt.Sprintf(
"This field is required because '%s' is set",
requiredIf,
),
Path: []string{propertyID},
}
}
}
if len(property.RequiredIfNot()) > 0 {
foundSet := false
for _, requiredIfNot := range property.RequiredIfNot() {
if _, set := rawData[requiredIfNot]; set {
foundSet = true
break
}
}
if !foundSet {
if len(property.RequiredIfNot()) == 1 {
return &ConstraintError{
Message: fmt.Sprintf(
"This field is required because '%s' is not set",
property.RequiredIfNot()[0],
),
Path: []string{propertyID},
}
}
return &ConstraintError{
Message: fmt.Sprintf(
"This field is required because none of '%s' are set",
strings.Join(property.RequiredIfNot(), "', '"),
),
Path: []string{propertyID},
}
}
}
return nil
}
func (o *ObjectSchema) validatePropertyInterdependenciesIfSet(
rawData map[string]any,
propertyID string,
property *PropertySchema,
) error {
for _, conflict := range property.Conflicts() {
if _, set := rawData[conflict]; set {
return &ConstraintError{
Message: fmt.Sprintf(
"Field conflicts '%s', set one of the two, not both",
conflict,
),
Path: []string{propertyID},
}
}
}
return nil
}
func (o *ObjectSchema) invalidKeyError(value any) error {
validKeys := make([]string, len(o.PropertiesValue))
i := 0
for k := range o.PropertiesValue {
validKeys[i] = k
i++
}
return &ConstraintError{
Message: fmt.Sprintf(
"Invalid parameter '%v', expected one of: %s",
value,
strings.Join(validKeys, ", "),
),
}
}
// TypedObject is a serializable version of Object.
type TypedObject[T any] interface {
Object
TypedType[T]
Any() TypedObject[any]
}
// NewStructMappedObjectSchema creates an object schema that is tied to a specific struct. The values will be mapped to that struct
// when unserialized.
func NewStructMappedObjectSchema[T any](id string, properties map[string]*PropertySchema) *ObjectSchema {
validateObjectIsStruct[T]()
var defaultValue T
return &ObjectSchema{
IDValue: id,
PropertiesValue: properties,
defaultValues: extractObjectDefaultValues(properties),
defaultValue: defaultValue,
defaultValueType: reflect.TypeOf(&defaultValue).Elem(),
fieldCache: buildObjectFieldCache[T](properties),
}
}
func NewTypedObject[T any](id string, properties map[string]*PropertySchema) *TypedObjectSchema[T] {
objectSchema := NewStructMappedObjectSchema[T](id, properties)
return &TypedObjectSchema[T]{
*objectSchema,
}
}
type TypedObjectSchema[T any] struct {
ObjectSchema `json:",inline"`
}
func (t TypedObjectSchema[T]) UnserializeType(data any) (T, error) {
data, err := t.ObjectSchema.Unserialize(data)
if err != nil {
var defaultValue T
return defaultValue, err
}
return data.(T), err
}
func (t TypedObjectSchema[T]) ValidateType(data T) error {
return t.ObjectSchema.Validate(data)
}
func (t TypedObjectSchema[T]) SerializeType(data T) (any, error) {
return t.ObjectSchema.Serialize(data)
}
func (t TypedObjectSchema[T]) Any() TypedObject[any] {
return &AnyTypedObject[T]{
t.ObjectSchema,
}
}
// AnyTypedObject is an object that pretends to be typed, but accepts any type.
type AnyTypedObject[T any] struct {
ObjectSchema `json:",inline"`
}
func (a *AnyTypedObject[T]) UnserializeType(data any) (any, error) {
return a.ObjectSchema.Unserialize(data)
}
func (a *AnyTypedObject[T]) ValidateType(data any) error {
return a.ObjectSchema.Validate(data)
}
func (a *AnyTypedObject[T]) SerializeType(data any) (any, error) {
return a.ObjectSchema.Serialize(data)
}
func (a *AnyTypedObject[T]) Any() TypedObject[any] {
return a
}
// ConvertToObjectSchema attempts to extract an ObjectSchema from the input.
//
// If an ObjectSchema is found, it returns it.
// If a RefSchema is found, it extracts the cached object schema the ref is referencing.
// If a ScopeSchema is found, it extracts the root object schema.
// Returns the ObjectSchema and true if successful, otherwise nil and false.
func ConvertToObjectSchema(typeOrData any) (Object, bool) {
// Try plain object schema
objectSchemaType, ok := typeOrData.(*ObjectSchema)
if ok {
return objectSchemaType, true
}
// Next, try ref schema
refSchemaType, ok := typeOrData.(*RefSchema)
if ok {
return refSchemaType.GetObject(), true
}
// Next, try scope schema.
scopeSchemaType, ok := typeOrData.(*ScopeSchema)
if ok {
return scopeSchemaType.RootObject(), true
}
// Try extracting the inlined ObjectSchema for types that have an ObjectSchema, like TypedObjectSchema.
value := reflect.ValueOf(typeOrData)
if reflect.Indirect(value).Kind() == reflect.Struct {
field := reflect.Indirect(value).FieldByName("ObjectSchema")
if field.IsValid() {
fieldAsInterface := field.Interface()
objectType, ok2 := fieldAsInterface.(ObjectSchema)
if ok2 {
objectSchemaType = &objectType
ok = true
}
}
}
return objectSchemaType, ok
}
func validateObjectIsStruct[T any]() {
var defaultValue T
reflectValue := reflect.TypeOf(defaultValue)
if reflectValue.Kind() == reflect.Pointer {
reflectValue = reflectValue.Elem()
}
if reflectValue.Kind() != reflect.Struct {
panic(BadArgumentError{
Message: fmt.Sprintf(
"NewStructMappedObjectSchema should only be called with a struct type, %T given",
defaultValue,
),
})
}
}
func extractObjectDefaultValues(properties map[string]*PropertySchema) map[string]any {
defaultValues := map[string]any{}
for propertyID, property := range properties {
if property.Default() != nil {
var value any
defaultValue := *property.Default()
propertyType := property.TypeID()
err := jsonUnmarshal(defaultValue, &value, propertyType)
if err != nil {
panic(BadArgumentError{
Message: fmt.Sprintf("Default value for property %s is not a valid JSON", propertyID),
Cause: err,
})
}
defaultValues[propertyID] = value
}
}
return defaultValues
}
func jsonUnmarshal(defaultValue string, value any, propertryType TypeID) error {
err := json.Unmarshal([]byte(defaultValue), &value)
if err != nil && propertryType == "string" {
// attempt to fix yaml string to valid JSON
defaultValueTypeString := ("\"" + defaultValue + "\"")
err2 := json.Unmarshal([]byte(defaultValueTypeString), &value)
if err2 != nil {
return fmt.Errorf("{%s} additional attempt to format string with additional quotes failed:{%s}",
err.Error(), err2.Error())
} else {
return nil
}
}
return err
}
func buildObjectFieldCache[T any](properties map[string]*PropertySchema) map[string]reflect.StructField {
var defaultValue T
fieldCache := make(map[string]reflect.StructField, len(properties))
reflectType := reflect.TypeOf(defaultValue)
if reflectType.Kind() == reflect.Pointer {
reflectType = reflectType.Elem()
}
for propertyID := range properties {
field, ok := reflectType.FieldByNameFunc(func(s string) bool {
fieldType, _ := reflectType.FieldByName(s)
jsonTag := fieldType.Tag.Get("json")
if jsonTag != "" {
parts := strings.SplitN(jsonTag, ",", 2)
if parts[0] == propertyID {
return true
}
}
return false
})
if !ok {
field, ok = reflectType.FieldByName(propertyID)
if !ok {
panic(BadArgumentError{
Message: fmt.Sprintf(
"Cannot find a valid field to set for '%s' on '%s'. Please name a field identically "+
"or provide a `json:\"%s\"` tag.",
propertyID,
reflectType.Name(),
propertyID,
),
})
}
}
fieldCache[propertyID] = field
}
return fieldCache
}