generated from go-masonry/mortar-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcurrency_converter.go
65 lines (55 loc) · 1.81 KB
/
currency_converter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package validations
import (
"context"
"go.uber.org/multierr"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"reflect"
currencyconverter "github.com/bevgene/go-currency-rate/api"
"github.com/go-masonry/mortar/interfaces/log"
"go.uber.org/fx"
)
type (
CurrencyRateValidations interface {
ValidateGetCurrencyRateRequest(ctx context.Context, request *currencyconverter.ConvertRequest) error
}
currencyRateValidationsImplDeps struct {
fx.In
Logger log.Logger
}
currencyRateValidationsImpl struct {
deps currencyRateValidationsImplDeps
}
)
func CreateCurrencyRateValidations(deps currencyRateValidationsImplDeps) CurrencyRateValidations {
return ¤cyRateValidationsImpl{
deps: deps,
}
}
func (impl *currencyRateValidationsImpl) ValidateGetCurrencyRateRequest(ctx context.Context, request *currencyconverter.ConvertRequest) (err error) {
return combineErrors(
impl.notEmpty(ctx, request.GetCurrencyTo(), "currencyTo"),
impl.notEmpty(ctx, request.GetCurrencyFrom(), "currencyFrom"),
func() error {
if request.GetAmountFrom() < 0 {
impl.deps.Logger.WithField("amount", request.GetAmountFrom()).Error(ctx, "amount cannot be negative")
return status.Errorf(codes.InvalidArgument, "negative amount")
}
return nil
}(),
)
}
func combineErrors(errs ...error) (err error) {
combinedErrors := multierr.Combine(errs...)
if actualErrors := multierr.Errors(combinedErrors); len(actualErrors) > 0 {
err = actualErrors[0]
}
return
}
func (impl *currencyRateValidationsImpl) notEmpty(ctx context.Context, value interface{}, fieldName string) (err error) {
if value == reflect.Zero(reflect.TypeOf(value)).Interface() {
impl.deps.Logger.WithField(fieldName, value).Error(ctx, "cannot be empty")
err = status.Errorf(codes.InvalidArgument, "%s cannot be empty", fieldName)
}
return
}