jmattheis / goverter

Generate type-safe Go converters by simply defining an interface
https://goverter.jmattheis.de/
MIT License
496 stars 46 forks source link

Embedded structs #24

Closed dansimau closed 1 year ago

dansimau commented 2 years ago

I have the following scenario:

package example

// goverter:converter
type Converter interface {
    ConvertPerson(source *Person) *APIPerson
}

type Address struct {
    Street string
    City   string
}

type Person struct {
    *Address

    Name string
}

type APIPerson struct {
    Name   string
    Street string
    City   string
}

How can I use goverter to map from a Person to an APIPerson?

I am facing two problems:

  1. Mapping pointer values to non-pointer values
  2. Manually listing all embedded fields

For (1) ideally I would like the target values to either be ignored or set to zero values if the source is nil. For (2) can I somehow map the fields in goverter without having to list them out one by one? I played with mapIdentity but it wasn't clear from the README if this applies to my situation, since it seems like the reverse.

Thanks in advance for your help.

jmattheis commented 2 years ago

You could do it like this:

// goverter:converter
// goverter:extend EmptyIfNilString
type Converter interface {
    // goverter:map Address.City City
    // goverter:map Address.Street Street
    ConvertPerson(source *Person) *APIPerson
}

func EmptyIfNilString(s *string) string {
    if s == nil {
        return ""
    }
    return *s
}

The goverter:extend method will be used for every *string to string conversion.

I think goverter could support some kind of auto mapping for nested fields which have the same field names, but this is currently not supported.

jmattheis commented 1 year ago

Closed in favor of: https://github.com/jmattheis/goverter/issues/55