goext/wmo/reflection.go
2023-06-07 17:48:36 +02:00

114 lines
2.4 KiB
Go

package wmo
import (
"gogs.mikescher.com/BlackForestBytes/goext/langext"
"gogs.mikescher.com/BlackForestBytes/goext/reflectext"
"reflect"
"strings"
)
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 {
continue
}
if strings.Contains(bsonkey, ",") {
bsonkey = bsonkey[:strings.Index(bsonkey, ",")]
}
if 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,
RealType: rvfield.Type(),
Kind: rvfield.Type().Elem().Kind(),
Type: rvfield.Type().Elem(),
UnderlyingType: reflectext.Underlying(rvfield.Type().Elem()),
Name: rsfield.Name,
Index: newIdxArr,
}
} else {
c.dataTypeMap[fullKey] = fullTypeRef[TData]{
IsPointer: false,
RealType: rvfield.Type(),
Kind: rvfield.Type().Kind(),
Type: rvfield.Type(),
UnderlyingType: reflectext.Underlying(rvfield.Type()),
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) {
fref := c.dataTypeMap[fieldName]
pss := reflectext.PrimitiveStringSerializer{}
return pss.ValueFromString(value, fref.RealType)
}
func (c *Coll[TData]) getFieldValueAsTokenString(entity TData, fieldName string) (string, error) {
realValue := c.getFieldValue(entity, fieldName)
pss := reflectext.PrimitiveStringSerializer{}
return pss.ValueToString(realValue)
}
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()
}