API package refactor
This commit is contained in:
parent
a7cd86962e
commit
bc6b57bc54
14 changed files with 474 additions and 416 deletions
91
apis/polls.go
Normal file
91
apis/polls.go
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
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)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue