92 lines
1.5 KiB
Go
92 lines
1.5 KiB
Go
|
|
package apis
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"net/http"
|
||
|
|
"planner/core"
|
||
|
|
|
||
|
|
"github.com/gin-gonic/gin"
|
||
|
|
)
|
||
|
|
|
||
|
|
func getPoll(c *gin.Context) {
|
||
|
|
user := extractUser(db, c)
|
||
|
|
if user == nil {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
var params struct {
|
||
|
|
PollId uint `uri:"poll_id"`
|
||
|
|
}
|
||
|
|
|
||
|
|
bind_result := c.BindUri(¶ms)
|
||
|
|
if bind_result != nil {
|
||
|
|
fmt.Println(bind_result)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
fmt.Println(params)
|
||
|
|
|
||
|
|
poll, _ := core.GetPoll(db, *user, params.PollId)
|
||
|
|
c.JSON(http.StatusOK, poll)
|
||
|
|
}
|
||
|
|
|
||
|
|
func getPollVotes(c *gin.Context) {
|
||
|
|
user := extractUser(db, c)
|
||
|
|
if user == nil {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
var params struct {
|
||
|
|
PollId uint `uri:"poll_id"`
|
||
|
|
}
|
||
|
|
|
||
|
|
bind_result := c.BindUri(¶ms)
|
||
|
|
if bind_result != nil {
|
||
|
|
fmt.Println(bind_result)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
var votes []core.Vote
|
||
|
|
db.Where("poll_id = ?", params.PollId).Find(&votes)
|
||
|
|
c.JSON(http.StatusOK, &votes)
|
||
|
|
}
|
||
|
|
|
||
|
|
func pollVote(c *gin.Context) {
|
||
|
|
user := extractUser(db, c)
|
||
|
|
if user == nil {
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
var path_params struct {
|
||
|
|
PollId uint `uri:"poll_id"`
|
||
|
|
}
|
||
|
|
|
||
|
|
bind_result := c.BindUri(&path_params)
|
||
|
|
if bind_result != nil {
|
||
|
|
fmt.Println(bind_result)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
poll, err := core.GetPoll(db, *user, path_params.PollId)
|
||
|
|
if err != nil {
|
||
|
|
c.String(http.StatusInternalServerError, err.Error())
|
||
|
|
return
|
||
|
|
}
|
||
|
|
|
||
|
|
var vote_params struct {
|
||
|
|
Vote string `json:"vote"`
|
||
|
|
}
|
||
|
|
c.Bind(&vote_params)
|
||
|
|
|
||
|
|
if err := poll.SetVote(db, *user, vote_params.Vote); err != nil {
|
||
|
|
c.String(http.StatusBadRequest, err.Error())
|
||
|
|
}
|
||
|
|
|
||
|
|
c.Status(http.StatusOK)
|
||
|
|
}
|
||
|
|
|
||
|
|
func bindPollAPIs(r *gin.Engine) {
|
||
|
|
r.GET("/polls/:poll_id", getPoll)
|
||
|
|
r.GET("/polls/:poll_id/votes", getPollVotes)
|
||
|
|
r.POST("/polls/:poll_id/votes", pollVote)
|
||
|
|
}
|