dtos

package
v0.211.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2024 License: Apache-2.0 Imports: 7 Imported by: 0

README

Data Transfer Objects (DTOs) Package

This package provides an easy-to-use and maintainable way to create DTOs and map between entities and their corresponding DTOs in Go applications. The package simplifies the process of creating DTOs, while ensuring type safety and reducing the potential for errors.

Features

  • Simplified creation of Data Transfer Objects (DTOs)
  • Mapping between entities and DTOs using custom mapping functions
  • Automatic handling of nested entities
  • Type-safe DTO creation and mapping
  • Support for multiple DTO mappings for different serialization formats, such as JSON or YAML
  • Ability to register multiple DTOs for a single entity

Getting Started

To get started, import the package into your Go application:

import "go.llib.dev/frameless/pkg/dtos"
Registering Mapping

The dtos.Register function is used to register the mappings between entities and their respective DTOs. In this example, we're using a JSONMapping object to contain the mapping configurations:

var JSONMapping dtos.M
var _ = dtos.Register[Ent, EntDTO](&JSONMapping, EntMapping{})
var _ = dtos.Register[NestedEnt, NestedEntDTO](&JSONMapping, NestedEntMapping{})
Defining Mappings

The mappings are defined using custom mapping functions for each entity-DTO pair:

package exampe

type Ent struct {
	V int
}

type EntDTO struct {
	V string `json:"v"`
}

type EntMapping struct{}

func (EntMapping) ToDTO(_ *dtos.M, ent Ent) (EntDTO, error) {
	return EntDTO{V: strconv.Itoa(ent.V)}, nil
}

func (EntMapping) ToEnt(m *dtos.M, dto EntDTO) (Ent, error) {
	v, err := strconv.Atoi(dto.V)
	if err != nil {
		return Ent{}, err
	}
	return Ent{V: v}, nil
}
Using Different Mapping Registries Per Serialization Formats

The package allows you to register different mappings for different serialization formats, such as JSON or YAML, or for different use cases. This makes it easy to maintain and update your mappings over time even if got a larger number of DTO models.

Here is an example of how to register a JSON-specific mapping and a YAML-specific mapping:

var JSONMapping dtos.M
_ = dtos.Register[Ent, EntJSONDTO](&JSONMapping, EntJSONMapping{})

var YAMLMapping dtos.M
_ = dtos.Register[Ent, EntYAMLDTO](&YAMLMapping, EntYAMLMapping{})

You can utilise distinct mapping registers as various mapping versions, simplifying the versioning process for your endpoint.

Using a Single Mapping Registry For Multiple Serialization Formats

The package also allows you to use a single mapping registry (dtos.M) to manage all your DTO mappings. This can be useful when you have moderate number of DTOs, and want to keep things simple.

Here is an example:

var DTOMappings dtos.M
var _ = dtos.Register[Ent, EntJSONDTO](&DTOMappings, EntJSONMapping{})
var _ = dtos.Register[Ent, EntYAMLDTO](&DTOMappings, EntYAMLMapping{})
Mapping Entities to DTOs & Marshalling

The dtos.Map function is used to convert an entity object into a target DTO object.

Once the DTO has been created, it can be marshaled into a the target format. For Example in case of json you can use Go's built-in json.Marshal function:

package exampe

func fn() {
	var v = NestedEnt{
		ID: "42",
		Ent: Ent{
			V: 42,
		},
	}

	dto, err := dtos.Map[NestedEntDTO](&JSONMapping, v)
	if err != nil { // handle err
		return
	}

	data, err := json.Marshal(dto)
	if err != nil { // handle error
		return
	}
	/*
		{
			"id": "42",
			"ent": {
				"v": "42"
			}
		}
	*/
}

Documentation

Index

Examples

Constants

View Source
const ErrNoMapping errorkit.Error = "[dtos] missing mapping"

Variables

This section is empty.

Functions

func Map

func Map[To, From any](ctx context.Context, from From) (_ To, returnErr error)
Example
package main

import (
	"context"
	"go.llib.dev/frameless/pkg/dtos"
	"strconv"
)

func main() {
	var _ = dtos.Register[Ent, EntDTO]( // only once at the global level
		EntMapping{}.ToDTO,
		EntMapping{}.ToEnt,
	)
	var (
		ctx = context.Background()
		ent = Ent{V: 42, N: 12}
	)

	dto, err := dtos.Map[EntDTO](ctx, ent)
	if err != nil {
		panic(err)
	}

	gotEnt, err := dtos.Map[Ent](ctx, dto)
	if err != nil {
		panic(err)
	}

	_ = gotEnt == ent // true
}

type Ent struct {
	V int
	N int
}

type EntDTO struct {
	V string `json:"v"`
	N int    `json:"n"`
}

type EntMapping struct{}

func (EntMapping) ToDTO(ctx context.Context, ent Ent) (EntDTO, error) {
	return EntDTO{V: strconv.Itoa(ent.V), N: ent.N}, 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, N: dto.N}, nil
}
Example (SliceSyntaxSugar)
package main

import (
	"context"
	"go.llib.dev/frameless/pkg/dtos"
	"strconv"
)

func main() {
	var _ = dtos.Register[Ent, EntDTO]( // only once at the global level
		EntMapping{}.ToDTO,
		EntMapping{}.ToEnt,
	)
	var (
		ctx  = context.Background()
		ents = []Ent{{V: 42, N: 12}}
	)

	// all individual value will be mapped
	res, err := dtos.Map[[]EntDTO](ctx, ents)
	if err != nil {
		panic(err)
	}
	_ = res // []EntDTO{V: "42", N: 12}
}

type Ent struct {
	V int
	N int
}

type EntDTO struct {
	V string `json:"v"`
	N int    `json:"n"`
}

type EntMapping struct{}

func (EntMapping) ToDTO(ctx context.Context, ent Ent) (EntDTO, error) {
	return EntDTO{V: strconv.Itoa(ent.V), N: ent.N}, 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, N: dto.N}, nil
}

func MustMap

func MustMap[To, From any](ctx context.Context, from From) To

func Register

func Register[From, To any](mapTo mapFunc[From, To], mapFrom mapFunc[To, From]) func()

Register function facilitates the registration of a mapping between two types. Optionally, if you don't intend to support bidirectional mapping, you can pass nil for the mapFrom argument. It's important to consider that supporting bidirectional mapping between an entity type and a DTO type often leads to the creation of non-partial DTO structures, enhancing their usability on the client side.

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
	N int
}

type EntDTO struct {
	V string `json:"v"`
	N int    `json:"n"`
}

type EntMapping struct{}

func (EntMapping) ToDTO(ctx context.Context, ent Ent) (EntDTO, error) {
	return EntDTO{V: strconv.Itoa(ent.V), N: ent.N}, 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, N: dto.N}, 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
}
Example (PartialDTOMappingSupport)
package main

import (
	"context"
	"go.llib.dev/frameless/pkg/dtos"
)

func main() {
	// When we only need an Entity to EntityPartialDTO mapping.
	dtos.Register[Ent, EntPartialDTO](EntToEntPartialDTO, nil)()

	var (
		ctx = context.Background()
		v   = Ent{V: 42, N: 12}
	)

	partialDTO, err := dtos.Map[EntPartialDTO](ctx, v)
	_, _ = partialDTO, err
}

type Ent struct {
	V int
	N int
}

type EntPartialDTO struct {
	N int `json:"n"`
}

func EntToEntPartialDTO(ctx context.Context, ent Ent) (EntPartialDTO, error) {
	return EntPartialDTO{N: ent.N}, nil
}

Types

type ErrMustMap

type ErrMustMap struct{ Err error }

func (ErrMustMap) Error

func (err ErrMustMap) Error() string

type MK

type MK struct {
	From reflect.Type
	To   reflect.Type
}

type MP added in v0.188.0

type MP interface {
	FromType() reflect.Type
	ToType() reflect.Type
}

type P added in v0.188.0

type P[A, B any] struct{}

P is a Mapping pair

func (P[A, B]) FromType added in v0.188.0

func (p P[A, B]) FromType() reflect.Type

FromType specify that P[A] is the form type.

func (P[A, B]) MapA added in v0.188.0

func (p P[A, B]) MapA(ctx context.Context, v B) (A, error)

func (P[A, B]) MapB added in v0.188.0

func (p P[A, B]) MapB(ctx context.Context, v A) (B, error)

func (P[A, B]) NewA added in v0.188.0

func (p P[A, B]) NewA() *A

func (P[A, B]) NewB added in v0.188.0

func (p P[A, B]) NewB() *B

func (P[A, B]) ToType added in v0.188.0

func (p P[A, B]) ToType() reflect.Type

ToType specify that P[B] is the form type.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL