-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_proposals.go
94 lines (78 loc) · 2.2 KB
/
list_proposals.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
package election
import (
"context"
"github.com/inklabs/cqrs"
"go.opentelemetry.io/otel/attribute"
"github.com/inklabs/vote/internal/electionrepository"
)
// ListProposals returns a paginated result of election proposals.
// Sortable options are omitted for this example.
type ListProposals struct {
ElectionID string
Page *int
ItemsPerPage *int
}
func (q ListProposals) ValidationRules() cqrs.ValidationRuleMap {
return cqrs.ValidationRuleMap{
"Page": cqrs.OptionalValidMinRange(1),
"ItemsPerPage": cqrs.OptionalValidRange(1, 10),
}
}
type ListProposalsResponse struct {
Proposals []Proposal
TotalResults int
}
type Proposal struct {
ElectionID string
ProposalID string
OwnerUserID string
Name string
Description string
ProposedAt int
}
type listProposalsHandler struct {
repository electionrepository.Repository
}
func NewListProposalsHandler(repository electionrepository.Repository) *listProposalsHandler {
return &listProposalsHandler{
repository: repository,
}
}
func (h *listProposalsHandler) On(ctx context.Context, query ListProposals) (ListProposalsResponse, error) {
ctx, span := tracer.Start(ctx, "vote.list-proposals")
defer span.End()
page, itemsPerPage := cqrs.DefaultPagination(query.Page, query.ItemsPerPage, electionrepository.DefaultItemsPerPage)
span.SetAttributes(
attribute.Int("page", page),
attribute.Int("itemsPerPage", itemsPerPage),
)
totalResults, proposals, err := h.repository.ListProposals(ctx,
query.ElectionID,
page,
itemsPerPage,
)
if err != nil {
return ListProposalsResponse{}, err
}
return ListProposalsResponse{
Proposals: ToProposals(proposals),
TotalResults: totalResults,
}, nil
}
func ToProposals(repoProposals []electionrepository.Proposal) []Proposal {
proposals := make([]Proposal, len(repoProposals))
for i := range repoProposals {
proposals[i] = ToProposal(repoProposals[i])
}
return proposals
}
func ToProposal(proposal electionrepository.Proposal) Proposal {
return Proposal{
ElectionID: proposal.ElectionID,
OwnerUserID: proposal.OwnerUserID,
ProposalID: proposal.ProposalID,
Name: proposal.Name,
Description: proposal.Description,
ProposedAt: proposal.ProposedAt,
}
}