-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserializer_gorm.go
72 lines (67 loc) · 2.26 KB
/
serializer_gorm.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
package cdt
import (
"context"
"encoding/json"
"reflect"
"gorm.io/gorm/schema"
)
type gormSerializerValuerInterface interface {
Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue any) (any, error)
}
type gormSerializerInterface interface {
Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue any) error
gormSerializerValuerInterface
}
// Scan ctx: contains request-scoped values
// field: the field using the serializer, contains GORM settings, struct tags
// dst: current model value, `user` in the below example
// dbValue: current field's value in database
func (c *DataRaw) Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue any) error {
c.OriginVal = dbValue
configTagKV := parseConfigCdtTagToKV(field.StructField)
if len(configTagKV) > 0 {
currentFieldValueRef := reflect.ValueOf(c)
if isPtr(currentFieldValueRef) || isInterface(currentFieldValueRef) {
for isPtr(currentFieldValueRef) || isInterface(currentFieldValueRef) {
currentFieldValueRef = currentFieldValueRef.Elem()
}
}
decodeDataForCdtTagKV(currentFieldValueRef, configTagKV)
}
return nil
}
// Value ctx: contains request-scoped values
// field: the field using the serializer, contains GORM settings, struct tags
// dst: current model value, `user` in the below example
// fieldValue: current field's value of the dst
func (c *DataRaw) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue any) (any, error) {
if fieldValue == nil {
return nil, nil
}
refVal := reflect.ValueOf(fieldValue)
switch refVal.Kind() {
case reflect.Ptr:
return c.Value(ctx, field, dst, refVal.Elem())
default:
val := refVal.Interface()
switch val.(type) {
case DataRaw:
sourceDataRaw := val.(DataRaw)
if sourceDataRaw.IsPtr() {
return c.Value(ctx, field, dst, *NewConvert(sourceDataRaw.GetOriginValRef().Elem().Interface()))
}
if sourceDataRaw.IsNil() || sourceDataRaw.IsString() ||
sourceDataRaw.IsBoolean() || sourceDataRaw.IsBytes() ||
sourceDataRaw.IsTime() {
return sourceDataRaw.OriginVal, nil
}
if sourceDataRaw.IsNumeric() {
return sourceDataRaw.ToFloat64E()
}
str, _ := sourceDataRaw.ToStringE()
return str, nil
default:
return json.Marshal(fieldValue)
}
}
}