-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmapify.go
283 lines (220 loc) · 7.23 KB
/
mapify.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
// (c) 2022 Jacek Olszak
// This code is licensed under MIT license (see LICENSE for details)
// Package mapify converts structs (and other maps) into maps.
package mapify
import (
"fmt"
"reflect"
"strconv"
)
// Mapper represents instance of mapper
type Mapper struct {
ShouldConvert ShouldConvert
Filter Filter
Rename Rename
MapValue MapValue
}
// ShouldConvert returns true when value should be converted to map. The value can be a struct, map[string]any or slice.
type ShouldConvert func(path string, value reflect.Value) (bool, error)
// Filter returns true when element should be included. If error is returned then the whole conversion is aborted
// and wrapped error is returned from Mapper.MapAny method.
type Filter func(path string, e Element) (bool, error)
// Rename renames element name. If error is returned then the whole conversion is aborted
// and wrapped error is returned from Mapper.MapAny method.
type Rename func(path string, e Element) (string, error)
// MapValue maps (transforms) element value. If error is returned then the whole conversion is aborted
// and wrapped error is returned from Mapper.MapAny method.
type MapValue func(path string, e Element) (interface{}, error)
// Element represents either a map entry, field of a struct or unnamed element of a slice.
type Element struct {
name string
field *reflect.StructField
reflect.Value
}
// Name returns field name of a struct, key of a map or empty string, when it represents element of a slice.
func (e Element) Name() string {
return e.name
}
// StructField returns the reflect.StructField if e represents a field of a struct. If not, ok is false.
func (e Element) StructField() (_ reflect.StructField, ok bool) {
if e.field == nil {
return reflect.StructField{}, false
}
return *e.field, true
}
// MapAny maps any object (struct, map, slice etc.) by converting each struct found to a map.
//
// * for struct the returned type will be map[string]interface{}
// * for slice of structs the returned type will be []map[string]interface{}
func (i Mapper) MapAny(v interface{}) (interface{}, error) {
return i.newInstance().mapAny("", v)
}
func (i Mapper) mapAny(path string, v interface{}) (interface{}, error) {
reflectValue := reflect.ValueOf(v)
switch {
case reflectValue.Kind() == reflect.Struct ||
(reflectValue.Kind() == reflect.Ptr && reflectValue.Elem().Kind() == reflect.Struct):
shouldConvert, err := i.ShouldConvert(path, reflectValue)
if err != nil {
return nil, fmt.Errorf("ShouldConvert failed: %w", err)
}
if !shouldConvert {
return reflectValue.Interface(), nil
}
return i.mapStruct(path, reflectValue)
case reflectValue.Kind() == reflect.Map && reflectValue.Type().Key().Kind() == reflect.String:
shouldConvert, err := i.ShouldConvert(path, reflectValue)
if err != nil {
return nil, fmt.Errorf("ShouldConvert failed: %w", err)
}
if !shouldConvert {
return reflectValue.Interface(), nil
}
return i.mapStringMap(path, reflectValue)
case reflectValue.Kind() == reflect.Slice:
return i.mapSlice(path, reflectValue)
default:
return v, nil
}
}
func (i Mapper) newInstance() Mapper {
if i.ShouldConvert == nil {
i.ShouldConvert = convertAll
}
if i.Filter == nil {
i.Filter = acceptAllFields
}
if i.Rename == nil {
i.Rename = noRename
}
if i.MapValue == nil {
i.MapValue = interfaceValue
}
return i
}
func (i Mapper) mapStruct(path string, reflectValue reflect.Value) (map[string]interface{}, error) {
result := map[string]interface{}{}
reflectValue = dereference(reflectValue)
reflectType := reflectValue.Type()
for j := 0; j < reflectType.NumField(); j++ {
field := reflectType.Field(j)
if !field.IsExported() {
continue
}
fieldName := field.Name
fieldPath := path + "." + fieldName
value := reflectValue.Field(j)
element := Element{name: fieldName, Value: value, field: &field}
if err := i.mapElement(fieldPath, element, result); err != nil {
return nil, err
}
}
return result, nil
}
func dereference(value reflect.Value) reflect.Value {
for value.Kind() == reflect.Ptr {
value = value.Elem()
}
return value
}
func (i Mapper) mapStringMap(path string, reflectValue reflect.Value) (map[string]interface{}, error) {
result := map[string]interface{}{}
keys := reflectValue.MapKeys()
for _, key := range keys {
fieldName := key.String()
fieldPath := path + "." + fieldName
value := reflectValue.MapIndex(key)
element := Element{name: fieldName, Value: value}
if err := i.mapElement(fieldPath, element, result); err != nil {
return nil, err
}
}
return result, nil
}
func (i Mapper) mapElement(fieldPath string, element Element, result map[string]interface{}) error {
accepted, filterErr := i.Filter(fieldPath, element)
if filterErr != nil {
return fmt.Errorf("Filter failed: %w", filterErr)
}
if accepted {
renamed, renameErr := i.Rename(fieldPath, element)
if renameErr != nil {
return fmt.Errorf("Rename failed: %w", renameErr)
}
mappedValue, mapErr := i.MapValue(fieldPath, element)
if mapErr != nil {
return fmt.Errorf("MapValue failed: %w", mapErr)
}
finalValue, err := i.mapAny(fieldPath, mappedValue)
if err != nil {
return err
}
result[renamed] = finalValue
}
return nil
}
func (i Mapper) mapSlice(path string, reflectValue reflect.Value) (_ interface{}, err error) {
kind := reflectValue.Type().Elem().Kind()
switch kind {
case reflect.Struct:
shouldConvert, err := i.ShouldConvert(path, reflectValue)
if err != nil {
return nil, fmt.Errorf("ShouldConvert failed: %w", err)
}
if !shouldConvert {
return reflectValue.Interface(), nil
}
slice := make([]map[string]interface{}, reflectValue.Len())
for j := 0; j < reflectValue.Len(); j++ {
slice[j], err = i.mapStruct(slicePath(path, j), reflectValue.Index(j))
if err != nil {
return nil, err
}
}
return slice, nil
case reflect.Map:
if reflectValue.Type().Elem().Key().Kind() != reflect.String {
return reflectValue.Interface(), nil
}
shouldConvert, err := i.ShouldConvert(path, reflectValue)
if err != nil {
return nil, fmt.Errorf("ShouldConvert failed: %w", err)
}
if !shouldConvert {
return reflectValue.Interface(), nil
}
slice := make([]map[string]interface{}, reflectValue.Len())
for j := 0; j < reflectValue.Len(); j++ {
slice[j], err = i.mapStringMap(slicePath(path, j), reflectValue.Index(j))
if err != nil {
return nil, err
}
}
return slice, nil
case reflect.Slice:
sliceElem := reflectValue.Type().Elem().Elem()
if sliceElem.Kind() == reflect.Struct ||
(sliceElem.Kind() == reflect.Map && sliceElem.Key().Kind() == reflect.String) {
shouldConvert, err := i.ShouldConvert(path, reflectValue)
if err != nil {
return nil, fmt.Errorf("ShouldConvert failed: %w", err)
}
if !shouldConvert {
return reflectValue.Interface(), nil
}
var slice [][]map[string]interface{}
for j := 0; j < reflectValue.Len(); j++ {
indexValue, err := i.mapSlice(slicePath(path, j), reflectValue.Index(j))
if err != nil {
return nil, err
}
slice = append(slice, indexValue.([]map[string]interface{}))
}
return slice, nil
}
}
return reflectValue.Interface(), nil
}
func slicePath(path string, index int) string {
return path + "[" + strconv.Itoa(index) + "]"
}