dtos

package
v0.185.0 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2024 License: Apache-2.0 Imports: 6 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](m *M, from From) (_ To, returnErr error)

func MustMap

func MustMap[To, From any](m *M, from From) To

func Register

func Register[Ent, DTO any](m *M, mapping Mapping[Ent, DTO]) func()
Example
package main

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

func main() {
	// JSONMapping will contain mapping from entities to JSON DTO structures.
	var JSONMapping dtos.M
	// registering Ent <---> EntDTO mapping
	_ = dtos.Register[Ent, EntDTO](&JSONMapping, EntMapping{})
	// registering NestedEnt <---> NestedEntDTO mapping, which includes the mapping of the nested entities
	_ = dtos.Register[NestedEnt, NestedEntDTO](&JSONMapping, NestedEntMapping{})

	var v = NestedEnt{
		ID: "42",
		Ent: Ent{
			V: 42,
		},
	}

	dto, err := dtos.Map[NestedEntDTO](&JSONMapping, 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(_ *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
}

type NestedEnt struct {
	ID  string
	Ent Ent
}

type NestedEntDTO struct {
	ID  string `json:"id"`
	Ent EntDTO `json:"ent"`
}

type NestedEntMapping struct{}

func (NestedEntMapping) ToEnt(m *dtos.M, dto NestedEntDTO) (NestedEnt, error) {
	return NestedEnt{
		ID:  dto.ID,
		Ent: dtos.MustMap[Ent](m, dto.Ent),
	}, nil
}

func (NestedEntMapping) ToDTO(m *dtos.M, ent NestedEnt) (NestedEntDTO, error) {
	return NestedEntDTO{
		ID:  ent.ID,
		Ent: dtos.MustMap[EntDTO](m, ent.Ent),
	}, nil
}

Types

type ErrMustMap

type ErrMustMap struct{ Err error }

func (ErrMustMap) Error

func (err ErrMustMap) Error() string

type M

type M struct {
	// contains filtered or unexported fields
}

func (*M) FromMappings

func (m *M) FromMappings(v any) []MK

func (*M) Map

func (m *M) Map(fromType, toType reflect.Type, from any) (_ reflect.Value, returnErr error)

type MK

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

type Mapping

type Mapping[Ent, DTO any] interface {
	ToEnt(*M, DTO) (Ent, error)
	ToDTO(*M, Ent) (DTO, error)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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