jmattheis / goverter

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

Passthrough additional data to the conversion methods #76

Closed pavelpatrin closed 1 year ago

pavelpatrin commented 1 year ago

I have a Job model, it has set of Task IDs stored in []int field.

I want to calculate some task statistics in converter extension function using preloaded set of Tasks, but I have access only ti Job instance. Can I somehow passthrough preloaded tasks to use them while converting the job?

E.g., we can get them from the context, or another passed object or map.

// goverter:extend JobTaskStatsToPb
type Converter interface {
    JobToPb(context.Context, models.Job) taskspb.Job
}

func JobTaskStatsToPb(ctx context.Context, value models.JobTaskStats) taskspb.JobTaskStats {
    jobTaskIDs := value.TaskIDs
    tasksData := ctx.Value("TasksStorageCtxKey").(map[int]models.Task)
    ... use tasks data from context to calculate job task stats ...
    return calculatedJobTaskStats
}
jmattheis commented 1 year ago

I'd say this is a duplicate of https://github.com/jmattheis/goverter/issues/68 and the solution described in here is a little less type safe because of the casting required when using context.Context.