-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlist_open_elections.go
97 lines (82 loc) · 2.42 KB
/
list_open_elections.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 election
import (
"context"
"github.com/inklabs/cqrs"
"go.opentelemetry.io/otel/attribute"
"github.com/inklabs/vote/internal/electionrepository"
)
// ListOpenElections returns a paginated result of elections that are still open.
type ListOpenElections struct {
Page *int
ItemsPerPage *int
SortBy *string
SortDirection *string
}
func (q ListOpenElections) ValidationRules() cqrs.ValidationRuleMap {
return cqrs.ValidationRuleMap{
"SortBy": cqrs.OptionalValidValues(
"Name",
"CommencedAt",
),
"SortDirection": cqrs.OptionalValidSortDirection(),
"Page": cqrs.OptionalValidMinRange(1),
"ItemsPerPage": cqrs.OptionalValidRange(1, 50),
}
}
type ListOpenElectionsResponse struct {
OpenElections []OpenElection
TotalResults int
}
type OpenElection struct {
ElectionID string
OrganizerUserID string
Name string
Description string
CommencedAt int
}
type listOpenElectionsHandler struct {
repository electionrepository.Repository
}
func NewListOpenElectionsHandler(repository electionrepository.Repository) *listOpenElectionsHandler {
return &listOpenElectionsHandler{
repository: repository,
}
}
func (h *listOpenElectionsHandler) On(ctx context.Context, query ListOpenElections) (ListOpenElectionsResponse, error) {
ctx, span := tracer.Start(ctx, "vote.list-open-elections")
defer span.End()
page, itemsPerPage := cqrs.DefaultPagination(query.Page, query.ItemsPerPage, electionrepository.DefaultItemsPerPage)
span.SetAttributes(
attribute.Int("page", page),
attribute.Int("itemsPerPage", itemsPerPage),
)
totalResults, elections, err := h.repository.ListOpenElections(ctx,
page,
itemsPerPage,
query.SortBy,
query.SortDirection,
)
if err != nil {
return ListOpenElectionsResponse{}, err
}
return ListOpenElectionsResponse{
OpenElections: ToOpenElections(elections),
TotalResults: totalResults,
}, nil
}
func ToOpenElections(elections []electionrepository.Election) []OpenElection {
openElections := make([]OpenElection, len(elections))
for i := range elections {
openElections[i] = ToOpenElection(elections[i])
}
return openElections
}
func ToOpenElection(election electionrepository.Election) OpenElection {
return OpenElection{
ElectionID: election.ElectionID,
OrganizerUserID: election.OrganizerUserID,
Name: election.Name,
Description: election.Description,
CommencedAt: election.CommencedAt,
}
}