| name | kratos-mapper |
| description | Generates bidirectional mapper functions between protobuf DTOs and business models for go-kratos services. Creates type-safe conversions with proper field mapping. Use when implementing service layer mappers. |
// Request → Business Model
func {Entity}FromCreateRequest(req *pb.Create{Entity}Request) *biz.{Entity} {
return &biz.{Entity}{
Name: req.Name,
// Map fields...
}
}
// Business Model → Proto Response
func toProto{Entity}(e *biz.{Entity}) *pb.{Entity} {
return &pb.{Entity}{
Id: e.ID,
Name: e.Name,
// Map fields...
}
}
Request to Business Model:
func {Entity}FromCreateRequest(req *pb.Create{Entity}Request) *biz.{Entity}
func {Entity}FromUpdateRequest(req *pb.Update{Entity}Request, id uint64) *biz.{Entity}
Business Model to Proto:
func toProto{Entity}(e *biz.{Entity}) *pb.{Entity}
func toProto{Entities}(list []*biz.{Entity}) []*pb.{Entity}
List Options:
func NewList{Entities}Options(req *pb.List{Entities}Request) *biz.List{Entities}Options {
return &biz.List{Entities}Options{
Pagination: pagination.PaginationParams{
Offset: req.Offset,
Limit: req.Limit,
},
}
}
Pagination Meta:
func toProtoPaginationMeta(meta *pagination.PaginationMeta) *pb.PaginationMeta {
return &pb.PaginationMeta{
Total: meta.Total,
Offset: meta.Offset,
Limit: meta.Limit,
}
}
Proto → Business: {Entity}From{Operation}Request
- Example:
SymbolFromCreateRequest,ProductFromUpdateRequest
Business → Proto: toProto{Entity} or toProto{Entities}
- Example:
toProtoSymbol,toProtoSymbols
Options: NewList{Entities}Options
Helpers: toProto{Type} for common types
- Example:
toProtoPaginationMeta,toProtoTimestamp
IDs: uint64 ↔ uint64 (direct)
Strings: string ↔ string (direct)
Timestamps: time.Time ↔ *timestamppb.Timestamp
CreatedAt: timestamppb.New(e.CreatedAt)
Optional Fields: Use pointers
// Business has *string, proto has string
Email: func() string {
if e.Email != nil {
return *e.Email
}
return ""
}()
Enums: Map string to proto enum
Status: pb.Status(pb.Status_value[e.Status])
Single entity: internal/service/mapper.go (all mappers)
Multiple entities: internal/service/{entity}_mapper.go (per entity)
Keep mapper functions close to service handlers for easy reference.