-
Notifications
You must be signed in to change notification settings - Fork 1
/
survey.go
87 lines (76 loc) · 2.04 KB
/
survey.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
package main
import (
"fmt"
"time"
)
const (
surveyEndDuration = 60 * time.Second
)
//SurveyOption is
type SurveyOption struct {
ID int `json:"id"`
Text string `json:"text"`
Count int `json:"count"`
}
//Survey is
type Survey struct {
ID int
Text string `json:"text"`
Options []*SurveyOption `json:"options"`
Owner DataChannelUser `json:"owner"`
ParticipantCount int `json:"participantCount"`
Votes map[int]*SurveyOption `json:"votes"` // user id and option id
}
//ConvertMapForUser ...
func (survey *Survey) ConvertMapForUser(user *User) map[string]interface{} {
mapJSON := make(map[string]interface{})
mapJSON["id"] = survey.ID
mapJSON["text"] = survey.Text
mapJSON["options"] = survey.Options
mapJSON["owner"] = survey.Owner
mapJSON["participantCount"] = survey.ParticipantCount
if userVote := survey.Votes[user.ID]; userVote != nil {
mapJSON["userVote"] = userVote
}
return mapJSON
}
//ConvertToMap ...
func (survey *Survey) ConvertToMap() map[string]interface{} {
mapJSON := make(map[string]interface{})
mapJSON["id"] = survey.ID
mapJSON["text"] = survey.Text
mapJSON["options"] = survey.Options
mapJSON["owner"] = survey.Owner
mapJSON["participantCount"] = survey.ParticipantCount
mapJSON["votes"] = survey.convertVotesToMap()
return mapJSON
}
func (survey *Survey) convertVotesToMap() map[int]interface{} {
votes := make(map[int]interface{})
for key, value := range survey.Votes {
votes[key] = value.ID
}
return votes
}
//Vote ...
func (survey *Survey) Vote(user *User, optionID int) error {
var option *SurveyOption
for _, eachOption := range survey.Options {
if optionID == eachOption.ID {
option = eachOption
break
}
}
if option == nil {
return fmt.Errorf("option not found in survey, option ID : %d", optionID)
}
option.Count++
survey.Votes[user.ID] = option
survey.ParticipantCount++
return nil
}
//Vote is
type Vote struct {
SurveyID int `json:"surveyID"`
OptionID int `json:"optionID"`
}