浏览代码

改进代码

yjp 1 年之前
父节点
当前提交
77f6c86a43
共有 2 个文件被更改,包括 96 次插入57 次删除
  1. 65 6
      domain/object.go
  2. 31 51
      examples/binding/main.go

+ 65 - 6
domain/object.go

@@ -1,15 +1,53 @@
 package domain
 
-import "git.sxidc.com/service-supports/fserr"
+import (
+	"git.sxidc.com/go-framework/baize/logger"
+	"git.sxidc.com/service-supports/fserr"
+	"reflect"
+)
 
-type IDType interface {
-	~string | ~uint64
-}
+type Object interface{}
+
+func SetField[T any](object Object, fieldName string, value T) {
+	fieldValue, err := getObjectFieldValue(object, fieldName)
+	if err != nil {
+		logger.GetInstance().Error(err)
+		return
+	}
 
-type Object interface {
+	if !fieldValue.IsValid() || !fieldValue.CanSet() {
+		err := fserr.New("object字段" + fieldName + "无法赋值")
+		logger.GetInstance().Error(err)
+		return
+	}
+
+	fieldValue.Set(reflect.ValueOf(value))
 }
 
-// TODO 添加简化函数,通过字段名称设置和获取值
+func Field[T any](object Object, fieldName string) T {
+	var zero T
+
+	fieldValue, err := getObjectFieldValue(object, fieldName)
+	if err != nil {
+		logger.GetInstance().Error(err)
+		return zero
+	}
+
+	if !fieldValue.IsValid() {
+		err := fserr.New("object字段" + fieldName + "无法赋值")
+		logger.GetInstance().Error(err)
+		return zero
+	}
+
+	retValue, ok := fieldValue.Interface().(T)
+	if !ok {
+		err := fserr.New("object字段" + fieldName + "无法转换类型")
+		logger.GetInstance().Error(err)
+		return zero
+	}
+
+	return retValue
+}
 
 func ToConcreteObject[T Object](object Object) (T, error) {
 	concrete, ok := object.(T)
@@ -20,3 +58,24 @@ func ToConcreteObject[T Object](object Object) (T, error) {
 
 	return concrete, nil
 }
+
+func getObjectFieldValue(object Object, fieldName string) (*reflect.Value, error) {
+	dtoType := reflect.TypeOf(object)
+
+	if dtoType.Kind() != reflect.Ptr {
+		return nil, fserr.New("object必须是结构指针类型")
+	}
+
+	if dtoType.Kind() == reflect.Ptr && dtoType.Elem().Kind() != reflect.Struct {
+		return nil, fserr.New("object必须是结构指针类型")
+	}
+
+	dtoValue := reflect.ValueOf(object)
+	if !dtoValue.IsValid() {
+		return nil, fserr.New("object为nil")
+	}
+
+	fieldValue := dtoValue.Elem().FieldByName(fieldName)
+
+	return &fieldValue, nil
+}

+ 31 - 51
examples/binding/main.go

@@ -13,10 +13,10 @@ import (
 )
 
 // curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' "http://localhost:10000/test/v1/class/create"
-// curl -X PUT -H "Content-Type: application/json" -d '{"id":"f630ccff4e534cb6b6b015ff21b34437", "name":"test-new"}' "http://localhost:10000/test/v1/class/update"
+// curl -X PUT -H "Content-Type: application/json" -d '{"id":"1fb7faa332af42fd9a41856320c0d4af", "name":"test-new"}' "http://localhost:10000/test/v1/class/update"
 // curl -X GET "http://localhost:10000/test/v1/class/query?name=test-new&pageNo=0&pageSize=1"
-// curl -X GET "http://localhost:10000/test/v1/class/get?id=f630ccff4e534cb6b6b015ff21b34437"
-// curl -X DELETE "http://localhost:10000/test/v1/class/f630ccff4e534cb6b6b015ff21b34437/delete"
+// curl -X GET "http://localhost:10000/test/v1/class/get?id=1fb7faa332af42fd9a41856320c0d4af"
+// curl -X DELETE "http://localhost:10000/test/v1/class/1fb7faa332af42fd9a41856320c0d4af/delete"
 
 type CreateClassJsonBody struct {
 	Name string `json:"name" binding:"required"`
@@ -51,7 +51,7 @@ type ClassInfo struct {
 	Name string `json:"name"`
 }
 
-var classMap = make(map[string]*Class)
+var classMap = make(map[string]domain.Object)
 
 func main() {
 	app := baize.NewApplication(application.Config{
@@ -76,15 +76,10 @@ func main() {
 			}, nil
 		},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (string, error) {
-			e, err := domain.ToConcreteObject[*Class](objects[0])
-			if err != nil {
-				return "", err
-			}
-
-			e.ID = strutils.SimpleUUID()
-			classMap[e.ID] = e
-
-			return e.ID, nil
+			id := strutils.SimpleUUID()
+			domain.SetField(objects[0], "ID", id)
+			classMap[id] = objects[0]
+			return id, nil
 		},
 	})
 
@@ -101,14 +96,9 @@ func main() {
 			}, nil
 		},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (any, error) {
-			e, err := domain.ToConcreteObject[*Class](objects[0])
-			if err != nil {
-				return nil, err
-			}
-
-			delete(classMap, e.ID)
-
-			fmt.Println("Deleted Entity:" + e.ID)
+			id := domain.Field[string](objects[0], "ID")
+			delete(classMap, id)
+			fmt.Println("Deleted Entity:" + id)
 			return nil, nil
 		},
 	})
@@ -127,23 +117,20 @@ func main() {
 			}, nil
 		},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (any, error) {
-			e, err := domain.ToConcreteObject[*Class](objects[0])
-			if err != nil {
-				return nil, err
-			}
+			id := domain.Field[string](objects[0], "ID")
+			newName := domain.Field[string](objects[0], "Name")
 
-			existEntity, ok := classMap[e.ID]
+			existEntity, ok := classMap[id]
 			if !ok {
-				fmt.Println("Update Entity:" + e.ID)
+				fmt.Println("Update Entity:" + id)
 				fmt.Println("Not Find")
 				return nil, nil
 			}
 
-			existEntity.Name = e.Name
-			classMap[e.ID] = existEntity
+			domain.SetField(existEntity, "Name", newName)
 
-			fmt.Println("Update Entity:" + existEntity.ID)
-			fmt.Println("Name:" + existEntity.Name)
+			fmt.Println("Update Entity:" + id)
+			fmt.Println("Name:" + newName)
 
 			return nil, nil
 		},
@@ -162,16 +149,9 @@ func main() {
 			}, nil
 		},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (binding.InfosData[ClassInfo], error) {
-			classInfos := make([]ClassInfo, 0)
+			name := domain.Field[string](objects[0], "Name")
 
-			e, err := domain.ToConcreteObject[*Class](objects[0])
-			if err != nil {
-				return binding.InfosData[ClassInfo]{
-					Infos:      classInfos,
-					TotalCount: 0,
-					PageNo:     0,
-				}, err
-			}
+			classInfos := make([]ClassInfo, 0)
 
 			pageNo := binding.Field[int](dto, "PageNo")
 			pageSize := binding.Field[int](dto, "PageSize")
@@ -190,14 +170,17 @@ func main() {
 			findCount := 0
 
 			for _, existEntity := range classMap {
+				existID := domain.Field[string](existEntity, "ID")
+				existName := domain.Field[string](existEntity, "Name")
+
 				if findCount >= needFindCount {
 					break
 				}
 
 				if count >= startCount {
 					find := false
-					if strutils.IsStringNotEmpty(e.Name) {
-						if existEntity.Name == e.Name {
+					if strutils.IsStringNotEmpty(name) {
+						if existName == name {
 							find = true
 							findCount++
 						}
@@ -208,8 +191,8 @@ func main() {
 
 					if find {
 						classInfos = append(classInfos, ClassInfo{
-							ID:   existEntity.ID,
-							Name: existEntity.Name,
+							ID:   existID,
+							Name: existName,
 						})
 					}
 				}
@@ -238,17 +221,14 @@ func main() {
 			}, nil
 		},
 		ServiceFunc: func(c *api.Context, dto binding.DTO, objects []domain.Object) (*ClassInfo, error) {
-			e, err := domain.ToConcreteObject[*Class](objects[0])
-			if err != nil {
-				return &ClassInfo{}, err
-			}
+			id := domain.Field[string](objects[0], "ID")
 
 			classInfo := new(ClassInfo)
 			for _, existEntity := range classMap {
-				if existEntity.ID == e.ID {
+				if domain.Field[string](existEntity, "ID") == id {
 					classInfo = &ClassInfo{
-						ID:   existEntity.ID,
-						Name: existEntity.Name,
+						ID:   domain.Field[string](existEntity, "ID"),
+						Name: domain.Field[string](existEntity, "Name"),
 					}
 				}
 			}