feat: fix mapper bug.

This commit is contained in:
Bobo
2025-06-16 11:59:09 +08:00
parent be5aa063df
commit 38f3cb8a3b
3 changed files with 17 additions and 17 deletions

View File

@@ -4,12 +4,12 @@ import (
"github.com/jinzhu/copier"
)
type EnumTypeConverter[DTO ~string, MODEL ~int32] struct {
type EnumTypeConverter[DTO ~int32, MODEL ~string] struct {
nameMap map[int32]string
valueMap map[string]int32
}
func NewEnumTypeConverter[DTO ~string, MODEL ~int32](nameMap map[int32]string, valueMap map[string]int32) *EnumTypeConverter[DTO, MODEL] {
func NewEnumTypeConverter[DTO ~int32, MODEL ~string](nameMap map[int32]string, valueMap map[string]int32) *EnumTypeConverter[DTO, MODEL] {
return &EnumTypeConverter[DTO, MODEL]{
valueMap: valueMap,
nameMap: nameMap,
@@ -21,7 +21,7 @@ func (m *EnumTypeConverter[DTO, MODEL]) ToModel(dto *DTO) *MODEL {
return nil
}
find, ok := m.valueMap[string(*dto)]
find, ok := m.nameMap[int32(*dto)]
if !ok {
return nil
}
@@ -35,7 +35,7 @@ func (m *EnumTypeConverter[DTO, MODEL]) ToDto(model *MODEL) *DTO {
return nil
}
find, ok := m.nameMap[int32(*model)]
find, ok := m.valueMap[string(*model)]
if !ok {
return nil
}
@@ -45,8 +45,8 @@ func (m *EnumTypeConverter[DTO, MODEL]) ToDto(model *MODEL) *DTO {
}
func (m *EnumTypeConverter[DTO, MODEL]) NewConverterPair() []copier.TypeConverter {
srcType := MODEL(0)
dstType := DTO("")
srcType := MODEL("")
dstType := DTO(0)
fromFn := m.ToDto
toFn := m.ToModel

View File

@@ -43,17 +43,17 @@ func TestCopierMapper(t *testing.T) {
}
func TestEnumTypeConverter(t *testing.T) {
type DtoType string
type ModelType int32
type DtoType int32
type ModelType string
const (
DtoTypeOne DtoType = "One"
DtoTypeTwo DtoType = "Two"
DtoTypeOne DtoType = 1
DtoTypeTwo DtoType = 2
)
const (
ModelTypeOne ModelType = 1
ModelTypeTwo ModelType = 2
ModelTypeOne ModelType = "One"
ModelTypeTwo ModelType = "Two"
)
nameMap := map[int32]string{
@@ -71,10 +71,10 @@ func TestEnumTypeConverter(t *testing.T) {
dto := DtoTypeOne
model := converter.ToModel(&dto)
assert.NotNil(t, model)
assert.Equal(t, int32(1), int32(*model))
assert.Equal(t, "One", string(*model))
// 测试 ToModel 方法,传入不存在的值
dtoInvalid := DtoType("Three")
dtoInvalid := DtoType(3)
modelInvalid := converter.ToModel(&dtoInvalid)
assert.Nil(t, modelInvalid)
@@ -83,10 +83,10 @@ func TestEnumTypeConverter(t *testing.T) {
model = &tmpModelTwo
dtoResult := converter.ToDto(model)
assert.NotNil(t, dtoResult)
assert.Equal(t, "Two", string(*dtoResult))
assert.Equal(t, DtoType(2), *dtoResult)
// 测试 ToDto 方法,传入不存在的值
tmpModelThree := ModelType(3)
tmpModelThree := ModelType("Three")
modelInvalid = &tmpModelThree
dtoInvalidResult := converter.ToDto(modelInvalid)
assert.Nil(t, dtoInvalidResult)

View File

@@ -8,7 +8,7 @@ git tag jwtutil/v0.0.2
git tag id/v0.0.2
git tag slug/v0.0.1
git tag name_generator/v0.0.1
git tag mapper/v0.0.1
git tag mapper/v0.0.2
git tag password/v0.0.1
git tag entgo/v1.1.31