-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_create_duelist.go
78 lines (65 loc) · 2.57 KB
/
handler_create_duelist.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
package handlers
import (
"encoding/json"
"log/slog"
"net/http"
"github.com/JPauloMoura/Yu-Gi-Oh-Connect/internal/entities"
"github.com/JPauloMoura/Yu-Gi-Oh-Connect/internal/handlers/dto"
"github.com/JPauloMoura/Yu-Gi-Oh-Connect/pkg/errors"
"github.com/JPauloMoura/Yu-Gi-Oh-Connect/pkg/response"
)
// @Summary CreateDuelist
// @Description Realiza a criação de um novo perfil de duelista na plataforma. Todos os campos da body são requireds, exceto "presentation". As informações de endereço seram preenchidas automaticamentes com base no Cep informado.
// @Tags Duelist
// @Accept json
// @Produce json
// @param body body dto.CreateDuelistDTO true "CreateDuelistDTO Object"
// @Success 201 {object} entities.Duelist
// @Router /duelist [POST]
func (h HandlerDuelist) CreateDuelist(w http.ResponseWriter, r *http.Request) {
var requestBody dto.CreateDuelistDTO
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
slog.Error("failed to decode body", slog.String("error", err.Error()))
response.Encode(w, errors.Join(errors.ErrorInvalidRequest, err), http.StatusBadRequest)
return
}
if err := requestBody.Validate(); err != nil {
slog.Error("failed to validate duelist", slog.String("error", err.Error()))
response.Encode(w, err, http.StatusBadRequest)
return
}
var err error
requestBody.Address, err = h.svcCep.GetAddress(requestBody.Cep)
if err == errors.ErrorInvalidCep {
slog.Error("failed get address", slog.String("error", err.Error()))
response.Encode(w, err, http.StatusBadRequest)
return
}
if err != nil {
slog.Error("failed get address", slog.String("error", err.Error()))
response.Encode(w, err, http.StatusInternalServerError)
return
}
duelist := createEntityDuelistByDuelistDTO(requestBody)
duelistCreated, err := h.svcDuelist.CreateDuelist(duelist)
if err != nil {
slog.Error("failed to create duelist", slog.String("error", err.Error()), slog.Any("duelist", duelist))
response.Encode(w, err, http.StatusInternalServerError)
return
}
response.Encode(w, duelistCreated, http.StatusCreated)
}
func createEntityDuelistByDuelistDTO(dto dto.CreateDuelistDTO) entities.Duelist {
duelist := entities.NewDuelist()
duelist.Name = dto.Name
duelist.Presentation = dto.Presentation
duelist.BirthDate = dto.BirthDate
duelist.Contact.Email = dto.Email
duelist.Contact.Phone = dto.Phone
duelist.Address.Cep = dto.Address.Zipcode
duelist.Address.State = dto.Address.StateShortname
duelist.Address.City = dto.Address.City
duelist.Address.District = dto.Address.District
duelist.Address.Street = dto.Address.Street
return duelist
}