-
Notifications
You must be signed in to change notification settings - Fork 1
/
controller_votes.go
90 lines (77 loc) · 2.18 KB
/
controller_votes.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/kiyutink/sowhenthen/entities"
"github.com/kiyutink/sowhenthen/storage"
)
func (c *Controller) handleVotesCreateOne() http.HandlerFunc {
type request struct {
Options []string `json:"options"`
VoterName string `json:"voterName"`
}
type response struct {
PollId string `json:"pollId"`
Options []string `json:"options"`
VoterName string `json:"voterName"`
}
return func(w http.ResponseWriter, r *http.Request) {
pollId := chi.URLParam(r, "pollId")
req := request{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(fmt.Sprintf("error decoding json: %v", err)))
return
}
vote := entities.Vote{}
vote.PollId = pollId
vote.Options = req.Options
vote.VoterName = req.VoterName
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
_, err = c.storage.Vote.Create(ctx, vote)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("error creating vote: %v", err)))
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(response(vote))
}
}
func (c *Controller) handleVotesGetMany() http.HandlerFunc {
type response []struct {
PollId string `json:"pollId"`
Options []string `json:"options"`
VoterName string `json:"voterName"`
}
return func(w http.ResponseWriter, r *http.Request) {
pollId := chi.URLParam(r, "pollId")
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
votes, err := c.storage.Vote.GetMany(ctx, pollId)
if err != nil {
if notFoundErr := new(storage.NotFoundError); errors.As(err, ¬FoundErr) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
res := make(response, len(votes))
for i, vote := range votes {
res[i].Options = vote.Options
res[i].PollId = vote.PollId
res[i].VoterName = vote.VoterName
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(res)
}
}