github.com/go-email-validator/go-email-validator@v0.0.0-20230409163946-b8b9e6a0552e/pkg/presentation/presenter.go (about)

     1  package presentation
     2  
     3  import (
     4  	"github.com/go-email-validator/go-email-validator/pkg/ev"
     5  	"github.com/go-email-validator/go-email-validator/pkg/ev/evmail"
     6  	"github.com/go-email-validator/go-email-validator/pkg/presentation/converter"
     7  	"time"
     8  )
     9  
    10  // GetEmail converts string to evmail.Address
    11  type GetEmail func(email string) evmail.Address
    12  
    13  // Interface is a decorator to represent result in a form of some service
    14  type Interface interface {
    15  	Validate(email string, opts map[ev.ValidatorName]interface{}) (interface{}, error)
    16  	ValidateFromAddress(email evmail.Address, opts map[ev.ValidatorName]interface{}) (interface{}, error)
    17  }
    18  
    19  // NewPresenter creates presenter decorator
    20  func NewPresenter(getEmail GetEmail, validator ev.Validator, converter converter.Interface) Interface {
    21  	return presenter{
    22  		getEmail:  getEmail,
    23  		validator: validator,
    24  		converter: converter,
    25  	}
    26  }
    27  
    28  type presenter struct {
    29  	getEmail  func(email string) evmail.Address
    30  	validator ev.Validator
    31  	converter converter.Interface
    32  }
    33  
    34  func (p presenter) Validate(email string, opts map[ev.ValidatorName]interface{}) (interface{}, error) {
    35  	address := p.getEmail(email)
    36  
    37  	return p.ValidateFromAddress(address, opts)
    38  }
    39  
    40  func (p presenter) ValidateFromAddress(address evmail.Address, opts map[ev.ValidatorName]interface{}) (interface{}, error) {
    41  	start := time.Now()
    42  	validationResult := p.validator.Validate(ev.NewInputFromMap(address, opts))
    43  	elapsed := time.Since(start)
    44  
    45  	return p.converter.Convert(address, validationResult, converter.NewOptions(elapsed)), nil
    46  }