jmattheis / goverter

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

TypeMismatch: Cannot convert interface{} to interface{} #71

Closed JessedeJonge closed 1 year ago

JessedeJonge commented 1 year ago

Have you read the project readme?

Describe your question I have three layers: database, service and api

For the convertor from database -> service I am using the following custom function for json.RawMessages (empty by default JSONB columns):

func RawMessageToMapStringInterface(value json.RawMessage) map[string]interface{} {
    var res map[string]interface{}
    err := json.Unmarshal(value, &res)
    if err != nil {
        fmt.Println("Error unmarshal")
        return nil
    }
    return res
}

This fixes a panic panic: unsupported type interface{}

After that, I try to convert service layer to api layer but get error:

Error while creating converter method:
    func (/converter.ServiceToAPIConverter).ServiceToApi(source serviceStruct) apiStruct

|  service.User
|
|      | map[string]interface{}
|      |
|      |       | <mapvalue> interface{}
|      |       |
source.Settings[]
target.Settings[]
|      |       |
|      |       | <mapvalue> interface{}
|      |
|      | map[string]interface{}
|
| api.User

TypeMismatch: Cannot convert interface{} to interface{}

Any help ?

jmattheis commented 1 year ago

Goverter cannot know how to convert inteface{} to interface{} and thus fails. You must define the conversion method yourself. E.g.

package example

// goverter:converter
// goverter:extend ConvertInterface
type Converter interface {
    Convert(source Input) Output
}

type Input struct {
    Age  interface{}
}

type Output struct {
    Age  interface{}
}

func ConvertInterface(value interface{}) interface{} {
    // convert value 
    converted := value
    return converted
}
JessedeJonge commented 1 year ago

Thank you, unfortabetely I am still getting panics after implementing the ConvertInteterface method.

panic: unsupported type interface{}

goroutine 1 [running]:
github.com/jmattheis/goverter/xtype.toCode({0x1047c4fa0?, 0x104919b20?})
        /Users/jessedejonge/go/pkg/mod/github.com/jmattheis/goverter@v0.17.2/xtype/type.go:268 +0xc3c
github.com/jmattheis/goverter/xtype.toCode({0x1047c4fc8?, 0x140001e5600})
        /Users/jessedejonge/go/pkg/mod/github.com/jmattheis/goverter@v0.17.2/xtype/type.go:256 +0x2d4
github.com/jmattheis/goverter/xtype.Type.TypeAsJen({{0x1047c4fc8, 0x140001e5600}, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, ...})
        /Users/jessedejonge/go/pkg/mod/github.com/jmattheis/goverter@v0.17.2/xtype/type.go:248 +0x48
github.com/jmattheis/goverter/builder.(*Map).Build(0x1047834c0, {0x1047c4640, 0x140005f26e0}, 0x14000332540, 0x14000416600, 0x140004970e0, 0x14000496aa0)
jmattheis commented 1 year ago

Could you try out v0.17.3? It should be fixed there.

JessedeJonge commented 1 year ago

That worked. Thank you for the fix!