dto

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2020 License: MIT Imports: 4 Imported by: 2

README

Package for conversation different request forms to Service layer DTO (Data Transfer Object).

Structure tags (default dto) available for linking fields with different names in source or destination structure, also snake_case tags will be assigned to CamelCase.

For example:

type SignUpStep1Form struct {
	Firstname string `json:"firstname" validate:"attr=firstname,min=1,max=50" dto:"name"`
	Lastname  string `json:"lastname" validate:"attr=lastname,max=50"`
}

type SignUpStep2Form struct {
	Username  string `json:"username" validate:"attr=username,min=3,max=32"`
	Email     string `json:"email" validate:"attr=email,email" dto:"contact_email"`
}

type SignUpDTO struct {	
	Name             string
	Lastname         string
        Path             string `dto:"username"`
	ContactEmail     string  
}
	formDTO := SignUpDTO{}
	err := dto.RequestToDTO(&formDTO, &requestStep1, &requestStep2)

Controller

package controllers

import (
	"github.com/censync/go-api-structure/service"
	"github.com/censync/go-dto"
	"github.com/censync/go-validator"
	"github.com/gin-gonic/gin"
)

// Input JSON form with validation rules
type SignUpForm struct {
	Username  string `json:"username" validate:"attr=username,min=3,max=32"`
	Firstname string `json:"firstname" validate:"attr=firstname,min=1,max=50"`
	Lastname  string `json:"lastname" validate:"attr=lastname,max=50"`
	Email     string `json:"email" validate:"attr=email,email"`
}

type SignUpDTO struct {
	Username  string
	Firstname string
	Lastname  string
	Email     string
}

func TestMethod(ctx *gin.Context) {
	request := SignUpForm{}
	
    ctx.BindJSON(&request)

	errs := validator.Validate(&request)

	if !errs.IsEmpty() {
		ctx.JSON(400, errs)
		return
	}

	formDTO := SignUpDTO{}

	err := dto.RequestToDTO(&formDTO, &request)

	if err != nil {
		ctx.JSON(400, map[string]string{
			"error": err.Error(),
		})
		return
	}

	err = service.AppService().SignUp(&formDTO)

	if err != nil {
		ctx.JSON(400, map[string]string{
			"error": err.Error(),
		})
		return
	}

	ctx.Status(200)
	return
}

Service

func (s *Service) SignUp(dto *SignUpDTO) error {
	// Process user sign up
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RequestToDTO

func RequestToDTO(dst interface{}, src ...interface{}) error

func SetFieldTag

func SetFieldTag(tag string)

Change default tag `dto` to custom

Types

This section is empty.

Jump to

Keyboard shortcuts

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