goext/wmo/reflection.go

107 lines
2.3 KiB
Go
Raw Normal View History

2023-06-06 21:18:40 +02:00
package wmo
import (
"gogs.mikescher.com/BlackForestBytes/goext/langext"
2023-06-07 16:58:17 +02:00
"gogs.mikescher.com/BlackForestBytes/goext/reflectext"
2023-06-06 21:18:40 +02:00
"reflect"
)
func (c *Coll[TData]) init() {
c.dataTypeMap = make(map[string]fullTypeRef[TData])
example := *new(TData)
v := reflect.ValueOf(example)
c.initFields("", v, make([]int, 0))
}
func (c *Coll[TData]) initFields(prefix string, rval reflect.Value, idxarr []int) {
rtyp := rval.Type()
for i := 0; i < rtyp.NumField(); i++ {
rsfield := rtyp.Field(i)
rvfield := rval.Field(i)
if !rsfield.IsExported() {
continue
}
bsonkey, found := rsfield.Tag.Lookup("bson")
if !found || bsonkey == "-" {
continue
}
fullKey := prefix + bsonkey
newIdxArr := langext.ArrCopy(idxarr)
newIdxArr = append(newIdxArr, i)
if rvfield.Type().Kind() == reflect.Pointer {
c.dataTypeMap[fullKey] = fullTypeRef[TData]{
IsPointer: true,
2023-06-07 16:58:17 +02:00
RealType: rvfield.Type(),
2023-06-06 21:18:40 +02:00
Kind: rvfield.Type().Elem().Kind(),
Type: rvfield.Type().Elem(),
2023-06-07 16:58:17 +02:00
UnderlyingType: reflectext.Underlying(rvfield.Type().Elem()),
2023-06-06 21:18:40 +02:00
Name: rsfield.Name,
Index: newIdxArr,
}
} else {
c.dataTypeMap[fullKey] = fullTypeRef[TData]{
IsPointer: false,
2023-06-07 16:58:17 +02:00
RealType: rvfield.Type(),
2023-06-06 21:18:40 +02:00
Kind: rvfield.Type().Kind(),
Type: rvfield.Type(),
2023-06-07 16:58:17 +02:00
UnderlyingType: reflectext.Underlying(rvfield.Type()),
2023-06-06 21:18:40 +02:00
Name: rsfield.Name,
Index: newIdxArr,
}
}
if rvfield.Kind() == reflect.Struct {
c.initFields(fullKey+".", rvfield, newIdxArr)
}
}
}
func (c *Coll[TData]) getTokenValueAsMongoType(value string, fieldName string) (any, error) {
2023-06-07 16:58:17 +02:00
fref := c.dataTypeMap[fieldName]
2023-06-06 21:18:40 +02:00
2023-06-07 16:58:17 +02:00
pss := reflectext.PrimitiveStringSerializer{}
2023-06-06 21:18:40 +02:00
2023-06-07 16:58:17 +02:00
return pss.ValueFromString(value, fref.RealType)
2023-06-06 21:18:40 +02:00
}
func (c *Coll[TData]) getFieldValueAsTokenString(entity TData, fieldName string) (string, error) {
realValue := c.getFieldValue(entity, fieldName)
2023-06-07 16:58:17 +02:00
pss := reflectext.PrimitiveStringSerializer{}
2023-06-06 21:18:40 +02:00
2023-06-07 16:58:17 +02:00
return pss.ValueToString(realValue)
2023-06-06 21:18:40 +02:00
}
func (c *Coll[TData]) getFieldType(fieldName string) fullTypeRef[TData] {
return c.dataTypeMap[fieldName]
}
func (c *Coll[TData]) getFieldValue(data TData, fieldName string) any {
fref := c.dataTypeMap[fieldName]
rval := reflect.ValueOf(data)
return rval.FieldByIndex(fref.Index).Interface()
}