Closed waltcow closed 1 year ago
// goverter:converter
type Converter interface {
// goverter:mapExtend FullName ExtendFullName
Convert(source *Input) *Output
}
type Input struct { FirstName string LastName string } type Output struct { FullName string }
func ExtendFullName(source Input) string { return source.FirstName + " " + source.LastName }
goverter will simplify the input types until there isn't a pointer, and then do the mapping.
2. Could you give a real use-case for this? It doesn't seem like a blocking issue because you can always define the method with the full source type and then only reference a field from it.
@jmattheis
Protobuf
define my schema ,code generate by protoc-gen-go
will nested some fields in struct
eg:type User struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
DisplayName string `protobuf:"bytes,2,opt,name=displayName,proto3" json:"displayName,omitempty"`
Avatar string `protobuf:"bytes,3,opt,name=avatar,proto3" json:"avatar,omitempty"`
Car *Car `protobuf:"bytes,4,opt,name=car,proto3" json:"car,omitempty"`
}
type Car struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
}
when you want to map User.Car.Name
to UserDTO.CarName
,i will use annotation like mapExtend CarName GetUserCarName
, GetUserCarName
method signature as follow
func GetUserCarName(source User) string {
return User.Car.Name
}
User
contains nested fields like Mutex
, which is not recommended pass as value type
@jmattheis
func (c *ConverterImpl) mapextendInputToMapextendOutput(source mapextend.Input) mapextend.Output {
var mapextendOutput mapextend.Output
mapextendOutput.FullName = mapextend.ExtendFullName(&source)
...
return mapextendOutput
}
The input/source parameter is a non pointer and will copy the object.
With v0.12.0 it's possible to define a field mapping and do a conversion of the given fields. See https://goverter.jmattheis.de/#/conversion/custom?id=mapping-method so the second point from the first comment is solved.
@waltcow Could you try out v0.14.0? With this release, Goverter should prefer using struct pointers when building converter methods.
The syntax has slightly changed. Your Converter interface from the first comment should look like this:
// goverter:converter
type Converter interface {
// goverter:map . FullName | ExtendFullName
// goverter:map Age | DefaultAge
Convert(source *Input) *Output
// goverter:map LastName FullName | ExtendWithSpecName
ConvertMeta(source *Input) *OutputMeta
}
Currently
mapExtend
can not support pass pointer type of source as parametermapExtend
may support pass particular field of source as parameterCode generated