数据源不存在指定数据,生成目标结构体也需要生成对应的结构体,否则会丢失相关参数验证

This commit is contained in:
2025-03-21 16:48:16 +08:00
parent 0754f879e8
commit be6b8e644f
3 changed files with 74 additions and 14 deletions

View File

@ -35,23 +35,45 @@ func init() {
// Date : 15:12 2025/3/18
func Run(sourceData []byte, fieldList []StructField) ([]byte, error) {
handleInstance := &handle{
sourceData: sourceData,
fieldList: fieldList,
dynamicStruct: dynamicStructGenerate.NewStruct(),
sourceData: sourceData,
fieldList: fieldList,
parentFieldTable: map[string]bool{},
}
tagTable := map[string]string{}
for _, item := range fieldList {
tagTable[item.TargetPath] = handleInstance.generateTag(item)
// 检测当前字段是否是某一个字段的父级字段
for _, field := range fieldList {
if field.TargetPath == item.TargetPath {
continue
}
// 当前字段以itemTarget开头
if strings.HasPrefix(field.TargetPath, item.TargetPath) {
// item.TargetPath是父级字段
handleInstance.parentFieldTable[item.TargetPath] = true
}
}
}
handleInstance.dynamicStruct = dynamicStructGenerate.NewStruct(tagTable)
return handleInstance.Run()
}
type handle struct {
sourceData []byte
fieldList []StructField
dynamicStruct dynamicStructGenerate.Builder
formatVal string
sourceData []byte
fieldList []StructField
dynamicStruct dynamicStructGenerate.Builder
formatVal string
parentFieldTable map[string]bool // 父级字段路径表
}
// Run 执行验证
func (h *handle) Run() ([]byte, error) {
for _, field := range h.fieldList {
if h.parentFieldTable[field.TargetPath] {
// 中间层级字段, 无需额外处理
continue
}
if len(field.Errmsg) == 0 {
field.Errmsg = field.JsonTag + " : 参数校验不通过"
}
@ -70,12 +92,14 @@ func (h *handle) Run() ([]byte, error) {
if nil != err {
return nil, err
}
// 支持嵌套结构体
fieldTag := h.generateTag(field)
if nil == sourceValue {
// 没出现异常, 但是value为nil, 视作参数不存在处理
// TODO: 这里需要设置为对应类型的零值
h.dynamicStruct.AddField(field.JsonTag, "", "", fieldTag, false)
continue
}
// TODO : 支持嵌套结构体
fieldTag := h.generateTag(field)
h.dynamicStruct.AddField(field.JsonTag, "", sourceValue, fieldTag, false)
}
val := h.dynamicStruct.Build().New()
@ -104,11 +128,14 @@ func (h *handle) checkRequired(field StructField) (bool, bool) {
if isHasRequiredRule {
required = true
}
if required && !isHasRequiredRule {
// 必传, 但是没有必传校验规则
return true, true
if required {
if !isHasRequiredRule {
// 必传, 但是没有必传校验规则
return true, true
}
return true, false
}
return true, false
return false, false
}
// getSourceDataValue 获取源数据值