-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubfield.go
More file actions
67 lines (59 loc) · 1.61 KB
/
subfield.go
File metadata and controls
67 lines (59 loc) · 1.61 KB
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
package apijson
import (
"github.com/sfcompute/nodes-go/packages/respjson"
"reflect"
)
func getSubField(root reflect.Value, index []int, name string) reflect.Value {
strct := root.FieldByIndex(index[:len(index)-1])
if !strct.IsValid() {
panic("couldn't find encapsulating struct for field " + name)
}
meta := strct.FieldByName("JSON")
if !meta.IsValid() {
return reflect.Value{}
}
field := meta.FieldByName(name)
if !field.IsValid() {
return reflect.Value{}
}
return field
}
func setMetadataSubField(root reflect.Value, index []int, name string, meta Field) {
target := getSubField(root, index, name)
if !target.IsValid() {
return
}
if target.Type() == reflect.TypeOf(meta) {
target.Set(reflect.ValueOf(meta))
} else if respMeta := meta.toRespField(); target.Type() == reflect.TypeOf(respMeta) {
target.Set(reflect.ValueOf(respMeta))
}
}
func setMetadataExtraFields(root reflect.Value, index []int, name string, metaExtras map[string]Field) {
target := getSubField(root, index, name)
if !target.IsValid() {
return
}
if target.Type() == reflect.TypeOf(metaExtras) {
target.Set(reflect.ValueOf(metaExtras))
return
}
newMap := make(map[string]respjson.Field, len(metaExtras))
if target.Type() == reflect.TypeOf(newMap) {
for k, v := range metaExtras {
newMap[k] = v.toRespField()
}
target.Set(reflect.ValueOf(newMap))
}
}
func (f Field) toRespField() respjson.Field {
if f.IsMissing() {
return respjson.Field{}
} else if f.IsNull() {
return respjson.NewField("null")
} else if f.IsInvalid() {
return respjson.NewInvalidField(f.raw)
} else {
return respjson.NewField(f.raw)
}
}