Documentation
¶
Index ¶
Examples ¶
Constants ¶
View Source
const ErrNoMapping errorkit.Error = "[dtos] missing mapping"
Variables ¶
This section is empty.
Functions ¶
func Register ¶
Example ¶
package main import ( "context" "encoding/json" "go.llib.dev/frameless/pkg/dtos" "strconv" ) func main() { // JSONMapping will contain mapping from entities to JSON DTO structures. // registering Ent <---> EntDTO mapping _ = dtos.Register[Ent, EntDTO]( EntMapping{}.ToDTO, EntMapping{}.ToEnt, ) // registering NestedEnt <---> NestedEntDTO mapping, which includes the mapping of the nested entities _ = dtos.Register[NestedEnt, NestedEntDTO]( NestedEntMapping{}.ToDTO, NestedEntMapping{}.ToEnt, ) var v = NestedEnt{ ID: "42", Ent: Ent{ V: 42, }, } ctx := context.Background() dto, err := dtos.Map[NestedEntDTO](ctx, v) if err != nil { // handle err return } _ = dto // data mapped into a DTO and now ready for marshalling /* NestedEntDTO{ ID: "42", Ent: EntDTO{ V: "42", }, } */ data, err := json.Marshal(dto) if err != nil { // handle error return } _ = data /* { "id": "42", "ent": { "v": "42" } } */ } type Ent struct { V int } type EntDTO struct { V string `json:"v"` } type EntMapping struct{} func (EntMapping) ToDTO(ctx context.Context, ent Ent) (EntDTO, error) { return EntDTO{V: strconv.Itoa(ent.V)}, nil } func (EntMapping) ToEnt(ctx context.Context, dto EntDTO) (Ent, error) { v, err := strconv.Atoi(dto.V) if err != nil { return Ent{}, err } return Ent{V: v}, nil } type NestedEnt struct { ID string Ent Ent } type NestedEntDTO struct { ID string `json:"id"` Ent EntDTO `json:"ent"` } type NestedEntMapping struct{} func (NestedEntMapping) ToEnt(ctx context.Context, dto NestedEntDTO) (NestedEnt, error) { return NestedEnt{ ID: dto.ID, Ent: dtos.MustMap[Ent](ctx, dto.Ent), }, nil } func (NestedEntMapping) ToDTO(ctx context.Context, ent NestedEnt) (NestedEntDTO, error) { return NestedEntDTO{ ID: ent.ID, Ent: dtos.MustMap[EntDTO](ctx, ent.Ent), }, nil }
Types ¶
type ErrMustMap ¶
type ErrMustMap struct{ Err error }
func (ErrMustMap) Error ¶
func (err ErrMustMap) Error() string
Click to show internal directories.
Click to hide internal directories.