Implement getElectionResults
This commit is contained in:
@ -42,7 +42,9 @@ type CreateVotesRequest struct {
|
||||
}
|
||||
|
||||
// ElectionResultsResponse defines model for ElectionResultsResponse.
|
||||
type ElectionResultsResponse = map[string]interface{}
|
||||
type ElectionResultsResponse struct {
|
||||
Results *[]VotesForChoice `json:"results,omitempty"`
|
||||
}
|
||||
|
||||
// ErrorResponse defines model for ErrorResponse.
|
||||
type ErrorResponse struct {
|
||||
@ -56,6 +58,12 @@ type ErrorResponse struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// VotesForChoice defines model for VotesForChoice.
|
||||
type VotesForChoice struct {
|
||||
Choice string `json:"choice"`
|
||||
Votes int `json:"votes"`
|
||||
}
|
||||
|
||||
// CreateElectionJSONRequestBody defines body for CreateElection for application/json ContentType.
|
||||
type CreateElectionJSONRequestBody = CreateElectionRequest
|
||||
|
||||
|
@ -3,17 +3,27 @@ package models
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type VoteModelInterface interface {
|
||||
Insert(voterIdentity string, electionId int, choiceText string, tokens int) (int, error)
|
||||
Exists(voterIdentity string, electionID int) (bool, error)
|
||||
GetByElection(electionID int) (*[]Vote, error)
|
||||
}
|
||||
|
||||
type VoteModel struct {
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
type Vote struct {
|
||||
VoterIdentity string
|
||||
ElectionID int
|
||||
ChoiceText string
|
||||
Tokens int
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (v *VoteModel) Insert(voterIdentity string, electionId int, choiceText string, tokens int) (int, error) {
|
||||
tx, err := v.DB.Begin()
|
||||
if err != nil {
|
||||
@ -55,3 +65,43 @@ func (v *VoteModel) Exists(voterIdentity string, electionID int) (bool, error) {
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (v *VoteModel) GetByElection(electionID int) (*[]Vote, error) {
|
||||
query := `
|
||||
SELECT voter_identity, election_id, choice_text, tokens, created_at
|
||||
FROM votes
|
||||
WHERE election_id = ?
|
||||
`
|
||||
|
||||
rows, err := v.DB.Query(query, electionID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var votes []Vote
|
||||
for rows.Next() {
|
||||
var vote Vote
|
||||
err := rows.Scan(
|
||||
&vote.VoterIdentity,
|
||||
&vote.ElectionID,
|
||||
&vote.ChoiceText,
|
||||
&vote.Tokens,
|
||||
&vote.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
votes = append(votes, vote)
|
||||
}
|
||||
|
||||
if err = rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(votes) == 0 {
|
||||
return nil, sql.ErrNoRows
|
||||
}
|
||||
|
||||
return &votes, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user