-
Notifications
You must be signed in to change notification settings - Fork 34
/
mapper_object.go
380 lines (337 loc) · 10.9 KB
/
mapper_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
package mapper
import (
"encoding/json"
"errors"
"reflect"
"sync"
"time"
)
type mapperObject struct {
ZeroValue reflect.Value
DefaultTimeWrapper *TimeWrapper
typeWrappers []TypeWrapper
timeType reflect.Type
jsonTimeType reflect.Type
fieldNameMap sync.Map
registerMap sync.Map
setting *Setting
}
func NewMapper(opts ...Option) IMapper {
setting := NewSetting(opts...)
dm := mapperObject{
ZeroValue: reflect.Value{},
DefaultTimeWrapper: NewTimeWrapper(),
typeWrappers: []TypeWrapper{},
timeType: reflect.TypeOf(time.Now()),
jsonTimeType: reflect.TypeOf(JSONTime(time.Now())),
setting: setting,
}
dm.useWrapper(dm.DefaultTimeWrapper)
return &dm
}
// Mapper map and set value from struct fromObj to toObj
// not support auto register struct
func (dm *mapperObject) Mapper(fromObj, toObj interface{}) error {
fromElem := reflect.ValueOf(fromObj).Elem()
toElem := reflect.ValueOf(toObj).Elem()
if fromElem == dm.ZeroValue {
return errors.New("from obj is not legal value")
}
if toElem == dm.ZeroValue {
return errors.New("to obj is not legal value")
}
return dm.elemMapper(fromElem, toElem)
}
// AutoMapper mapper and set value from struct fromObj to toObj
// support auto register struct
func (dm *mapperObject) AutoMapper(fromObj, toObj interface{}) error {
return dm.Mapper(fromObj, toObj)
}
// MapperMap mapper and set value from map to object
// support auto register struct
// now support field type:
// 1.reflect.Bool
// 2.reflect.String
// 3.reflect.Int8\16\32\64
// 4.reflect.Uint8\16\32\64
// 5.reflect.Float32\64
// 6.time.Time
func (dm *mapperObject) MapperMap(fromMap map[string]interface{}, toObj interface{}) error {
toElemType := reflect.ValueOf(toObj)
toElem := toElemType
if toElemType.Kind() == reflect.Ptr {
toElem = toElemType.Elem()
}
if toElem == dm.ZeroValue {
return errors.New("to obj is not legal value")
}
// check register flag
// if not register, register it
if !dm.checkIsRegister(toElem) {
if err := dm.Register(toObj); err != nil {
return err
}
}
for k, v := range fromMap {
fieldName := k
// check field is exists
realFieldName, exists := dm.CheckExistsField(toElem, fieldName)
if !exists {
continue
}
fieldInfo, exists := toElem.Type().FieldByName(realFieldName)
if !exists {
continue
}
fieldKind := fieldInfo.Type.Kind()
fieldValue := toElem.FieldByName(realFieldName)
if err := dm.setFieldValue(fieldValue, fieldKind, v); err != nil {
return err
}
}
return nil
}
// SetEnabledTypeChecking set enabled flag for TypeChecking
// if set true, the field type will be checked for consistency during mapping
// default is false
func (dm *mapperObject) SetEnabledTypeChecking(isEnabled bool) {
dm.setting.EnabledTypeChecking = isEnabled
}
func (dm *mapperObject) IsEnabledTypeChecking() bool {
return dm.setting.EnabledTypeChecking
}
// SetEnabledMapperTag set enabled flag for 'Mapper' tag check
// if set true, 'Mapper' tag will be check during mapping's GetFieldName
// default is true
func (dm *mapperObject) SetEnabledMapperTag(isEnabled bool) {
dm.setting.EnabledMapperTag = isEnabled
dm.cleanRegisterValue()
}
func (dm *mapperObject) IsEnabledMapperTag() bool {
return dm.setting.EnabledMapperTag
}
// SetEnabledJsonTag set enabled flag for 'Json' tag check
// if set true, 'Json' tag will be check during mapping's GetFieldName
// default is true
func (dm *mapperObject) SetEnabledJsonTag(isEnabled bool) {
dm.setting.EnabledJsonTag = isEnabled
dm.cleanRegisterValue()
}
func (dm *mapperObject) IsEnabledJsonTag() bool {
return dm.setting.EnabledJsonTag
}
// SetEnabledAutoTypeConvert set enabled flag for auto type convert
// if set true, field will auto convert in Time and Unix
// default is true
func (dm *mapperObject) SetEnabledAutoTypeConvert(isEnabled bool) {
dm.setting.EnabledAutoTypeConvert = isEnabled
}
func (dm *mapperObject) IsEnabledAutoTypeConvert() bool {
return dm.setting.EnabledAutoTypeConvert
}
// SetEnabledMapperStructField set enabled flag for MapperStructField
// if set true, the reflect.Struct field will auto mapper
// must follow premises:
// 1. fromField and toField type must be reflect.Struct and not time.Time
// 2. fromField and toField must be not same type
// default is enabled
func (dm *mapperObject) SetEnabledMapperStructField(isEnabled bool) {
dm.setting.EnabledMapperStructField = isEnabled
}
func (dm *mapperObject) IsEnabledMapperStructField() bool {
return dm.setting.EnabledMapperStructField
}
// SetEnabledCustomTag set enabled flag for set custom tag name
// if set true and set customTagName, the custom tag will be check during mapping's GetFieldName
// default is false
func (dm *mapperObject) SetEnabledCustomTag(isEnabled bool) {
dm.setting.EnabledCustomTag = isEnabled
dm.cleanRegisterValue()
}
func (dm *mapperObject) IsEnabledCustomTag() bool {
return dm.setting.EnabledCustomTag
}
// SetCustomTagName
func (dm *mapperObject) SetCustomTagName(tagName string) {
dm.setting.CustomTagName = tagName
}
// SetEnableFieldIgnoreTag set the enabled flag for the ignored tag
// in the version < 0.7.8, we use field name as the key when mapping structs if field tag is "-"
// from 0.7.8, we add switch enableFieldIgnoreTag which is false in default
// if caller enable this flag, the field will be ignored in the mapping process
func (dm *mapperObject) SetEnableFieldIgnoreTag(isEnabled bool) {
dm.setting.EnableFieldIgnoreTag = isEnabled
}
func (dm *mapperObject) IsEnableFieldIgnoreTag() bool {
return dm.setting.EnableFieldIgnoreTag
}
// GetTypeName get type name
func (dm *mapperObject) GetTypeName(obj interface{}) string {
object := reflect.ValueOf(obj)
return object.String()
}
// GetCustomTagName get CustomTagName
func (dm *mapperObject) GetCustomTagName() string {
return dm.setting.CustomTagName
}
// GetFieldName get fieldName with ElemValue and index
// if config tag string, return tag value
func (dm *mapperObject) GetFieldName(objElem reflect.Value, index int) string {
return dm.getFieldName(objElem, index)
}
func (dm *mapperObject) GetDefaultTimeWrapper() *TimeWrapper {
return dm.DefaultTimeWrapper
}
// Register register struct to init Map
func (dm *mapperObject) Register(obj interface{}) error {
objValue := reflect.ValueOf(obj)
if objValue == dm.ZeroValue {
return errors.New("obj value does not exist")
}
return dm.registerValue(objValue)
}
// UseWrapper register a type wrapper
func (dm *mapperObject) UseWrapper(w TypeWrapper) {
if len(dm.typeWrappers) > 0 {
dm.typeWrappers[len(dm.typeWrappers)-1].SetNext(w)
}
dm.typeWrappers = append(dm.typeWrappers, w)
}
// MapToSlice mapper from map[string]interface{} to a slice of any type's ptr
// toSlice must be a slice of any type.
func (dm *mapperObject) MapToSlice(fromMap map[string]interface{}, toSlice interface{}) error {
var err error
toValue := reflect.ValueOf(toSlice)
if toValue.Kind() != reflect.Ptr {
return errors.New("toSlice must be a pointer to a slice")
}
if toValue.IsNil() {
return errors.New("toSlice must not be a nil pointer")
}
toElemType := reflect.TypeOf(toSlice).Elem().Elem()
realType := toElemType.Kind()
direct := reflect.Indirect(toValue)
if realType == reflect.Ptr {
toElemType = toElemType.Elem()
}
for _, v := range fromMap {
if reflect.TypeOf(v).Kind().String() == "map" {
elem := reflect.New(toElemType)
err = dm.MapperMap(v.(map[string]interface{}), elem.Interface())
if err == nil {
if realType == reflect.Ptr {
direct.Set(reflect.Append(direct, elem))
} else {
direct.Set(reflect.Append(direct, elem).Elem())
}
}
} else {
if realType == reflect.Ptr {
direct.Set(reflect.Append(direct, reflect.ValueOf(v)))
} else {
direct.Set(reflect.Append(direct, reflect.ValueOf(v).Elem()))
}
}
}
return err
}
// MapperMapSlice mapper from map[string]map[string]interface{} to a slice of any type's ptr
// toSlice must be a slice of any type.
// Deprecated: will remove on v1.0, please use MapToSlice instead
func (dm *mapperObject) MapperMapSlice(fromMaps map[string]map[string]interface{}, toSlice interface{}) error {
var err error
toValue := reflect.ValueOf(toSlice)
if toValue.Kind() != reflect.Ptr {
return errors.New("toSlice must be a pointer to a slice")
}
if toValue.IsNil() {
return errors.New("toSlice must not be a nil pointer")
}
toElemType := reflect.TypeOf(toSlice).Elem().Elem()
realType := toElemType.Kind()
direct := reflect.Indirect(toValue)
// 3 elem parse: 1.[]*type 2.*type 3.type
if realType == reflect.Ptr {
toElemType = toElemType.Elem()
}
for _, v := range fromMaps {
elem := reflect.New(toElemType)
err = dm.MapperMap(v, elem.Interface())
if err == nil {
if realType == reflect.Ptr {
direct.Set(reflect.Append(direct, elem))
} else {
direct.Set(reflect.Append(direct, elem.Elem()))
}
}
}
return err
}
// MapperSlice mapper from slice of struct to a slice of any type
// fromSlice and toSlice must be a slice of any type.
func (dm *mapperObject) MapperSlice(fromSlice, toSlice interface{}) error {
var err error
toValue := reflect.ValueOf(toSlice)
if toValue.Kind() != reflect.Ptr {
return errors.New("toSlice must be a pointer to a slice")
}
if toValue.IsNil() {
return errors.New("toSlice must not be a nil pointer")
}
elemType := reflect.TypeOf(toSlice).Elem().Elem()
realType := elemType.Kind()
direct := reflect.Indirect(toValue)
// 3 elem parse: 1.[]*type 2.*type 3.type
if realType == reflect.Ptr {
elemType = elemType.Elem()
}
fromElems := dm.convertToSlice(fromSlice)
for _, v := range fromElems {
elem := reflect.New(elemType).Elem()
if realType == reflect.Ptr {
elem = reflect.New(elemType)
}
if realType == reflect.Ptr {
err = dm.elemMapper(reflect.ValueOf(v).Elem(), elem.Elem())
} else {
err = dm.elemMapper(reflect.ValueOf(v), elem)
}
if err == nil {
direct.Set(reflect.Append(direct, elem))
}
}
return err
}
// MapToJson mapper from map[string]interface{} to json []byte
func (dm *mapperObject) MapToJson(fromMap map[string]interface{}) ([]byte, error) {
jsonStr, err := json.Marshal(fromMap)
if err != nil {
return nil, err
}
return jsonStr, nil
}
// JsonToMap mapper from json []byte to map[string]interface{}
func (dm *mapperObject) JsonToMap(body []byte, toMap *map[string]interface{}) error {
err := json.Unmarshal(body, toMap)
return err
}
// CheckExistsField check field is exists by name
func (dm *mapperObject) CheckExistsField(elem reflect.Value, fieldName string) (realFieldName string, exists bool) {
typeName := elem.Type().String()
fileKey := typeName + nameConnector + fieldName
realName, isOk := dm.fieldNameMap.Load(fileKey)
if !isOk {
return "", isOk
} else {
return realName.(string), isOk
}
}
// CheckIsTypeWrapper check value is in type wrappers
func (dm *mapperObject) CheckIsTypeWrapper(value reflect.Value) bool {
for _, w := range dm.typeWrappers {
if w.IsType(value) {
return true
}
}
return false
}