-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_update_duelist.go
97 lines (78 loc) · 2.52 KB
/
handler_update_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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package repository
import (
"log/slog"
"strconv"
"strings"
"github.com/JPauloMoura/Yu-Gi-Oh-Connect/internal/entities"
"github.com/JPauloMoura/Yu-Gi-Oh-Connect/pkg/errors"
)
func (r repository) UpdateDuelist(duelist entities.Duelist) error {
_, err := r.FindDuelist(duelist.Id)
if err != nil {
slog.Error("failed to check if the duelist", slog.Any("error", err), slog.String("id", duelist.Id))
return errors.ErrorDuelistNotFound
}
q, fields := generateQueryToUpdateDuelist(duelist)
query, err := r.db.Prepare(q)
if err != nil {
slog.Error("failed to prepare query to update duelist", slog.Any("error", err), slog.Any("duelist", duelist))
return errors.ErrorQueryToUpdateDuelistIsInvalid
}
_, err = query.Exec(fields...)
if err != nil {
slog.Error("failed to update duelist", slog.Any("error", err), slog.Any("duelist", duelist))
return errors.ErrorUnableToUpdateDuelist
}
return nil
}
func generateQueryToUpdateDuelist(duelist entities.Duelist) (string, []interface{}) {
query := "UPDATE duelists SET"
var values []interface{}
counter := 1
if duelist.Name != "" {
query += " name=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Name)
counter++
}
if duelist.Presentation != "" {
query += " presentation=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Presentation)
counter++
}
if duelist.Address.Cep != "" {
query += " cep=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Address.Cep)
counter++
query += " state=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Address.State)
counter++
query += " city=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Address.City)
counter++
query += " street=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Address.Street)
counter++
query += " district=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Address.District)
counter++
}
if !duelist.BirthDate.IsZero() {
query += " birthDate=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.BirthDate)
counter++
}
if duelist.Contact.Email != "" {
query += " email=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Contact.Email)
counter++
}
if duelist.Contact.Phone != "" {
query += " phone=$" + strconv.Itoa(counter) + ","
values = append(values, duelist.Contact.Phone)
counter++
}
query = strings.TrimSuffix(query, ",")
query += " WHERE id=$" + strconv.Itoa(counter)
values = append(values, duelist.Id)
return query, values
}