-
Notifications
You must be signed in to change notification settings - Fork 2
/
create_account.go
92 lines (75 loc) · 2.12 KB
/
create_account.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package action
import (
"encoding/json"
"net/http"
"strings"
"github.com/felixa1996/go-plate/adapter/api/logging"
"github.com/felixa1996/go-plate/adapter/api/response"
"github.com/felixa1996/go-plate/adapter/logger"
"github.com/felixa1996/go-plate/adapter/validator"
"github.com/felixa1996/go-plate/usecase"
)
type CreateAccountAction struct {
uc usecase.CreateAccountUseCase
log logger.Logger
validator validator.Validator
}
func NewCreateAccountAction(uc usecase.CreateAccountUseCase, log logger.Logger, v validator.Validator) CreateAccountAction {
return CreateAccountAction{
uc: uc,
log: log,
validator: v,
}
}
func (a CreateAccountAction) Execute(w http.ResponseWriter, r *http.Request) {
const logKey = "create_account"
var input usecase.CreateAccountInput
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
logging.NewError(
a.log,
err,
logKey,
http.StatusBadRequest,
).Log("error when decoding json")
response.NewError(err, http.StatusBadRequest).Send(w)
return
}
defer r.Body.Close()
if errs := a.validateInput(input); len(errs) > 0 {
logging.NewError(
a.log,
response.ErrInvalidInput,
logKey,
http.StatusBadRequest,
).Log("invalid input")
response.NewErrorMessage(errs, http.StatusBadRequest).Send(w)
return
}
a.cleanCPF(input.CPF)
output, err := a.uc.Execute(r.Context(), input)
if err != nil {
logging.NewError(
a.log,
err,
logKey,
http.StatusInternalServerError,
).Log("error when creating a new account")
response.NewError(err, http.StatusInternalServerError).Send(w)
return
}
logging.NewInfo(a.log, logKey, http.StatusCreated).Log("success creating account")
response.NewSuccess(output, http.StatusCreated).Send(w)
}
func (a CreateAccountAction) validateInput(input usecase.CreateAccountInput) []string {
var msgs []string
err := a.validator.Validate(input)
if err != nil {
for _, msg := range a.validator.Messages() {
msgs = append(msgs, msg)
}
}
return msgs
}
func (a CreateAccountAction) cleanCPF(cpf string) string {
return strings.Replace(strings.Replace(cpf, ".", "", -1), "-", "", -1)
}