diff --git a/pkg/internal/http/api/index.go b/pkg/internal/http/api/index.go index ca74957..5268925 100644 --- a/pkg/internal/http/api/index.go +++ b/pkg/internal/http/api/index.go @@ -71,6 +71,7 @@ func MapAPIs(app *fiber.App, baseURL string) { polls.Put("/:pollId", updatePoll) polls.Delete("/:pollId", deletePoll) polls.Post("/:pollId/answer", answerPoll) + polls.Get("/:pollId/answer", getMyPollAnswer) } subscriptions := api.Group("/subscriptions").Name("Subscriptions API") diff --git a/pkg/internal/http/api/polls_api.go b/pkg/internal/http/api/polls_api.go index 667e63b..25bfa96 100644 --- a/pkg/internal/http/api/polls_api.go +++ b/pkg/internal/http/api/polls_api.go @@ -12,6 +12,22 @@ import ( "github.com/gofiber/fiber/v2" ) +func getMyPollAnswer(c *fiber.Ctx) error { + if err := sec.EnsureAuthenticated(c); err != nil { + return err + } + user := c.Locals("user").(authm.Account) + + pollId, _ := c.ParamsInt("pollId") + + var answer models.PollAnswer + if err := database.C.Where("poll_id = ? AND account_id = ?", pollId, user.ID).First(&answer).Error; err != nil { + return fiber.NewError(fiber.StatusNotFound, err.Error()) + } + + return c.JSON(answer) +} + func getPoll(c *fiber.Ctx) error { pollId, _ := c.ParamsInt("pollId") diff --git a/pkg/internal/models/polls.go b/pkg/internal/models/polls.go index 02426ef..d43e4e9 100644 --- a/pkg/internal/models/polls.go +++ b/pkg/internal/models/polls.go @@ -18,8 +18,9 @@ type Poll struct { } type PollMetric struct { - TotalAnswer int64 `json:"total_answer"` - ByOptions map[string]int64 `json:"by_options"` + TotalAnswer int64 `json:"total_answer"` + ByOptions map[string]int64 `json:"by_options"` + ByOptionsPercentage map[string]float64 `json:"by_options_percentage"` } type PollOption struct { diff --git a/pkg/internal/services/polls.go b/pkg/internal/services/polls.go index a6330f7..d5adea1 100644 --- a/pkg/internal/services/polls.go +++ b/pkg/internal/services/polls.go @@ -49,8 +49,14 @@ func GetPollMetric(poll models.Poll) models.PollMetric { byOptions[answer.Answer]++ } + byOptionsPercentage := make(map[string]float64) + for _, option := range poll.Options { + byOptionsPercentage[option.ID] = float64(byOptions[option.ID]) / float64(len(answers)) + } + return models.PollMetric{ - TotalAnswer: int64(len(answers)), - ByOptions: byOptions, + TotalAnswer: int64(len(answers)), + ByOptions: byOptions, + ByOptionsPercentage: byOptionsPercentage, } }